• I’m having trouble to automatically log in a user that has been authenticated by an external source (which is being developed by me). It’s easy to reproduce the problem so I thought I’d explain how..

    I created the following filter:

    function test_authenticate($user, $username, $password) {
        return get_user_by('login', 'admin');
    }
    add_filter('authenticate', 'test_authenticate', 30, 3);

    Now, if I access: “http://my-domain/wp-login.php”, WP logs me in and I get redirected to: “http://my-domain/wp-admin/
    This is exactly what I want to happen!

    However, If I access: “http://my-domain/wp-admin/“, WP first redirects me to the login form URL which in this case is: “http://my-domain/wp-login.php?redirect_to=http://my-domain/wp-admin/&reauth=1

    Next, the above filter kicks in, but because of the redirect parameter in the URL I am not redirected to the dashboard, instead I end up at the login form again. The user should be created in the session but reloading the page doesn’t help.

    If I click the “Log in” button on the login form however (without entering any credentials as the above filter solves that) I get redirected to the dashboard.

    I solved this issue by making sure there is no redirect parameter in the URL by adding this:

    function test_login(){
        global $pagenow;
        if( 'wp-login.php' == $pagenow ) {
            $url = home_url($_SERVER['REQUEST_URI']);
            $urlp = parse_url($url);
            if (isset($urlp['query']) || !empty($urlp['query'])) {
                wp_redirect($urlp['path']);
            }
        }
    }
    add_action('init’,'test_login');

    The above function checks if wp-login.php is being rendered, if so it redirects the user to “login.php” if there are any query parameters. But this doesn’t feel like a good solution.. is there anything better I can do?

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    You are bounced back to the login form because of the ‘reauth’ query parameter in the redirect URL.

    You could use the ‘login_redirect’ filter I believe. Besides the destination URL (2 variants), your callback is passed the supposed user object. If the user object is actually a WP_Error object, do nothing but return the original URL. The login form will display the error message.

    If the user object is in fact a valid WP_User object, then the login was successful and it is safe to strip off any ‘reauth’ query parameter that happens to be in the URL. Then the subsequent redirect will go to where ever the user originally intended to go without bouncing back to the login form.

Viewing 1 replies (of 1 total)

The topic ‘Automatically login user into admin by accessing wp-login.php’ is closed to new replies.