WordPress – After login with custom login form, to access the admin area wordpress asks me to re-authenticate, why?

I’m doing some practice and was trying to build a wordpress plugin that logs in with username and password. Everything works correctly, except that after authentication, to access the admin area, wordpress asks me to re-authenticate with the following redirect: wp-login.php?redirect_to=https%3A%2F%2Fmywebsite.com% 2Fwp-admin%2F&reauth=1

Reading around I understood that it could depend on an expired session token, or on a login session that is no longer valid. So I’ve been trying to work with the nonce to refresh the token. But I can’t solve the problem. I don’t want wordpress to ask me for re-authentication to access the admin area.

I don’t understand what I’m doing wrong and I’ve been lost for several days now. Can anyone help me shed some light on this?

Here is my code below:

PHP server side:

// Ajax action handler for login-form.php
function login_handler() {


   // Verify Nonce
   if ( !wp_verify_nonce( $_POST['nonce'], 'login-form-nonce' ) ){
      wp_send_json_error( array('message' => __( 'Invalid Token', 'text-domain' ) ) );
   }
   // Update token
   set_transient( 'login_token_expiration_' . $_POST['nonce'], time() + 3600, 3600 );
   
   // Verify exp token
   $expiration_date = get_transient( 'login_token_expiration_' . $_POST['nonce'] );
   if ( false === $expiration_date || time() > $expiration_date ) {
      delete_transient( 'login_token_expiration_' . $_POST['nonce'] );
      wp_send_json_error( array('message' => __( 'token expired', 'text-domain' ) ) );
   } 

  
   // rest of the login code
   $creds = array();
   $creds['user_login'] = $_POST['username'];
   $creds['user_password'] = $_POST['password'];
   $user = wp_signon( $creds, false );
   if ( is_wp_error($user) ){
      wp_send_json_error( array('message' => 'Wrong Email/username', 'text-domain' ) );
   } else{
      wp_send_json_success( array('message' => 'Login Success, redirect...', 'username' => $user->user_login) );
   }
   wp_die();
}

Javascript client side:

<div class="login-form-wrapper">
   <form id="login-form" method="post">
      <div class="login_form_fields uname">
         <label for="username">Email / Username</label>
         <input type="text" id="username" name="username" required>
      </div>
      <div class="login_form_fields pswrd">
         <label for="password">Password</label>
         <input type="password" id="password" name="password" required>
         <span id="password-toggle" class="fa-light fa-eye"></span>
      </div>   

      <input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'login-form-nonce' ); ?>">
      <div id="login-form-message"></div>
      <button class="login_button" type="submit">Login</button>
   </form>
</div>


jQuery(document).ready(function($) {
   $('#login-form').submit(function(e) {
      e.preventDefault(); // stop the form from submitting the normal way
      
      var form = $(this);
      var username = encodeURIComponent(form.find('#username').val());
      var email = encodeURIComponent(form.find('#email').val());
      var regex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$|^[A-Za-z0-9._-]+$/; 
      var isValid = regex.test(username) || regex.test(email);

      // Error Message if Wrong email or password
      if (!isValid) {
         $('#login-form-message').html("Username o email non validi");
         return;
      }
      
 
      // Data Object
      var data = {
         'action': 'login',
         'username': username,
         'password': form.find('#password').val(),
         'nonce': form.find('input[name="nonce"]').val()
      };

      $.ajax({
         type: 'POST',
         url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
         data: data,
         success: function(response) {
            if (response.success) {
               $('#login-form-message').html('<lottie-player src="https://assets9.lottiefiles.com/packages/lf20_ht6o1bdu.json" background="transparent" speed="1" style="width: 150px; height: 150px;" loop autoplay></lottie-player> Stai effettuando l\'accesso come ' + response.data.username); 
               setTimeout(function(){
                  //window.location.href = '/';
               }, 1500);
            } else {
               $('#login-form-message').html(response.data.message);
            }
         }
      });
   });
});

>Solution :

The issue with re-authentication is likely due to the session not being persistent. After the user logs in, you need to set the WordPress cookie to persist the session. You can use the following function (wp_set_auth_cookie()) after the user logs in:

wp_set_auth_cookie( $user->ID, true );

This will set the authentication cookie for the logged-in user and make the session persistent, preventing WordPress from asking for re-authentication.

Leave a Reply