Automatically login user into admin by accessing wp-login.php
-
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?
The topic ‘Automatically login user into admin by accessing wp-login.php’ is closed to new replies.