Leon’s Weblog

December 10, 2007

WordPress Auto-Login

Filed under: Software Dev — leon @ 9:31 pm

WordPressis a great blogging engine. It’s flexible, scalable, and easy to tweak/configure to integrate into an existing PHP site. However, if you have an existing site with available user authentication and management capabilities, getting WordPress to accept those credentials (in a single sign-on fashion) can be a bit of a challenge.

Before we proceed, I should note that there are a number of available plugins that enable WordPress to integrate with some of the popular content management systems out there. Our requirement is a bit different however. We want to bypass WordPress’ authentication mechanism all together and have users login through the main portion of the site. In fact, in a well integrated site, the interface should make navigating between WordPress pages and the rest of the site seamless to the user. Our goal is to write a WordPress plug-in that will automatically authenticate a user who is already logged into the parent site (and, consequently, grant the user access to edit the blog’s content). All other users will have the rights of an unregistered visitor.

In my setup, the main site has role-based permissions and the WordPress setup only has one account for each role (i.e. admin, editor, user etc…). The plugin first checks the role of the user logged in to the main site and then simulates a WordPress login anytime the user navigates to the blog. You should be able to customize this method for your own needs.

function auto_login() {
    if (!is_user_logged_in()) {
        //determine WordPress user account to impersonate
        $user_login = 'guest'; 

        //get users password
        $user = new WP_User(0, $user_login);
        $user_pass = md5($user->user_pass); 

        //login, set cookies, and set current user
        wp_login($user_login, $user_pass, true);
        wp_setcookie($user_login, $user_pass, true);
        wp_set_current_user($user->ID, $user_login);
    }
}
add_action('init', 'auto_login');

Additional notes and caveats for the attentive reader

  • There is a wp-include/pluggable.phpfile that defines all the functions that you can override and hook into. The WordPress API documentation is not very thorough so you may need to review the actual code.
  • WordPress uses a double MD5 hash of the password to authenticate the user. In the database, the password is stored as a single hash. We need to hash that password again before passing it into the wp_login() function (and set the third parameter to indicate that the password is already hashed). Obviously hard coding the actual password would be a big no-no.

We did all this work to login but what about logging out? We have several options. First, we can call WordPress’ logout method which is wp_clearcookie()from the main site.  The drawback to this approach is that we need to include all the WordPress libraries into our main site for this to work (too much unnecessary overhead IMHO). The other approach is to not use cookies at all thus alleviating the need to logout. To do this we simply remove the call to wp_setcookie()in out plugin and override the auth_redirect()function to do nothing. This works because we impersonate the user on every page load and the only WordPress code that checks the cookie was in auth_redirect()until we got rid of it. Another side effect of this is that un-authenticated WordPress users will no longer be taken to the WordPress login page (but we didn’t want that anyway).

Update 6/4/08: There were a few changes to the WordPress API as of version 2.5 and some of the functions I used above became depreciated. The API documentation has also improved. A better way to implement the auto_login() function above is as follows.

function auto_login() {
    if (!is_user_logged_in()) {
        //determine WordPress user account to impersonate
        $user_login = 'guest';

       //get user's ID
        $user = get_userdatabylogin($user_login);
        $user_id = $user->ID;
  
        //login
        wp_set_current_user($user_id, $user_login);
        wp_set_auth_cookie($user_id);
        do_action('wp_login', $user_login);
    }
} 
add_action('init', 'auto_login');

49 Comments »

  1. I’ve been searching for this auto-login feature for a while. Thanks for the help! ;)

    Comment by Mateus — March 27, 2008 @ 10:00 pm
  2. Thanks a ton for the tip

    Comment by Santosh — May 28, 2008 @ 12:26 pm
  3. I have been trying to figure out the auto login feature for a while. I am not a php programmer at all. The website I developed that I want to tie into the blog is in flash. I want to auto login in the background when a link is clicked from the Flash website.

    I looked at your code above and it looks interesting but how do I implement it?

    Thanks,

    Rob

    Comment by Rob McFaul — September 24, 2008 @ 8:00 am
  4. Rob, Save the auto_login() function in a .php file and place it in your WordPress plugins folder. You will have to enable the plugin using the WordPress configuration page. Good Luck.

    Comment by leon — September 24, 2008 @ 11:01 am
  5. Thanks. I am still confused slightly. I can pass variables from Flash to a PHP page. I want to send your plugin the User Name and Password from Flash.

    I am still not able to figure how to make that work with your script.

    Thanks,

    Rob

    Comment by Rob McFaul — September 24, 2008 @ 6:42 pm
  6. Hello there,
    I was just wondering, will this plugin work if the main site that the users are using to login is a .NET site? if not what shall I do to get it to work?
    Thanks,

    Kaly

    Comment by Kaly — October 16, 2008 @ 6:16 pm
  7. Kaly,
    The plugin will work as long as you can pass the desired user name and password to it. You can do this from .Net, Java, Flash or even CGI although its much easier if you use PHP. For a .Net site, why not use a native blog engine like BlogEngine.Net?

    Comment by leon — October 16, 2008 @ 6:27 pm
  8. Thanks for the reply Leon,
    Well I’m not a PHP programmer, I’m a .NET developer, and I’m doing that for a client of mine, the reason why I can’t use BlogEngine is simply because the client wants wordpress!
    Anyway, I’ll try this plugin, and I’ll let you know if it works or not :)
    Thanks!
    Kaly

    Comment by Kaly — October 17, 2008 @ 3:27 am
  9. I’m trying to implement this feature,

    though somehow it gives errors,

    I don’t have the password though, but it sets the cookies that are required,
    yet they are somehow different.

    My script is however not included in the wp scripting, its a side-script
    to auto logon a user trough Active Directory.

    wp_cache_init();
    $user = get_userdatabylogin($sUserName);
    $user_id = $user->ID;
    wp_set_current_user($user_id, $sUserName);
    wp_set_auth_cookie($user_id);
    do_action(‘wp_login’, $sUserName);

    It does not generate any errors, and gives a cookie, but the cookie is incorrect.

    Comment by Patrick — October 27, 2008 @ 9:30 am
  10. Hi,
    as first thanks for this tiny script. But how could I change this script? – I’ve got in my first site session-based login. I would like to pass-through the user without having a login-screen generated by wordpress?
    Thanks!

    Comment by Martin — December 1, 2008 @ 2:26 pm
  11. Martin, thats exactly what the script does. You just need to change the user names to match you site/WordPress setup. Good Luck.

    Comment by leon — December 1, 2008 @ 3:29 pm
  12. hi,
    Another smilar question needs your advice.

    I’m using WPMU, and I want to know how many times each user signs in.

    function test() {
    //global $current_user;
    //echo $current_user->ID;
    $user = wp_get_current_user();
    echo $user->ID;
    //update_usermeta($current_user->ID,’hook_test’,$_SERVER["REMOTE_ADDR"]);
    }
    add_action(‘wp_login’, ‘test’);

    But here I can’t get current user’s ID, any suggestions?

    Comment by copper — December 13, 2008 @ 1:22 am
  13. Duuude, I wasted so much time mucking around with pluggable.php before reading your post. This solution saved me! Bonus: Now I understand the basics behind WP plug-ins. Seems to work great with WordPress 2.6.5, thanks again!

    Comment by Jeff — December 17, 2008 @ 1:20 pm
  14. thanks for help.

    Comment by neelakshi — January 20, 2009 @ 1:49 am
  15. Hi Rob,

    I save the auto_login() function in the pluggable.php file and create a form to pass the values (see below) however nothing happen. Please Help.

    My code in the pluggable.php is:

    function auto_login() {
    if (!is_user_logged_in()) {
    //determine WordPress user account to impersonate
    $user_login = ‘guest’;

    //get user’s ID
    $user = get_userdatabylogin($user_login);
    $user_id = $user->ID;

    //login
    wp_set_current_user($user_id, $user_login);
    wp_set_auth_cookie($user_id);
    do_action(‘wp-login’, $user_login);
    }
    }

    add_action(‘wp-login’, ‘auto_login’);

    The code of the file with the form located in the my site root directory is,

    <?php
    echo ”;
    echo ”;
    echo ‘Username:’;
    echo ”;
    echo ‘Password:’;
    echo ”;
    echo ”;
    echo ”;
    echo ”;
    ?>

    Any help will be appreciated.

    Thanks,

    Javier

    Comment by Javier — January 29, 2009 @ 6:28 pm
  16. Sorry, I can’t post html code. But is basically a normal form with two fields (user_login & user_pass) and the action is pointing to “blog/wp-login.php”.

    Comment by Javier — January 29, 2009 @ 6:49 pm
  17. Hi Leon!

    Thanks for the tip! But – do you use this in practice? There are some problems that I have encountered:
    1) if you use function wp_insert_user() you need to use this line:
    require_once( ABSPATH . WPINC . ‘/registration.php’);
    2) how do you disable all of the login/logout/register stuff? I will cope with it tomorrow, I’ll try to find the hooks and redirect in them to my login/logout/register pages. Is there an easier way?

    I’m not sure if my idea is the same as yours – I’m using the code to login the user on each and every WP page he comes to. If the user does not exist in WP, I create his username on the spot.

    Any idea on point 2?

    Thanks, nice work!

    Comment by Andrew — February 9, 2009 @ 1:09 pm
  18. Andrew,
    I think the function that I use only gets called once when the Wordpress loads. I didn’t have to deal with the registration issues.

    Comment by leon — February 9, 2009 @ 1:55 pm
  19. Leon, thanks for the answer!

    I have solved it by making a redirect to my login/logout/forgotpass/register pages. Not extensible, but I couldn’t find a nicer way.

    Right now I’m having “fun” with set_role()… Looks like another long night ahead of me. :)

    Thanks, enjoy!
    (btw., your comment was not e-mailed to me – I guess that is on purpose? :) )

    Comment by Andrew — February 10, 2009 @ 5:43 am
  20. Just wanted to say thanks for the code. Works beautifully for me.

    Comment by Jason Coleman — March 30, 2009 @ 1:41 pm
  21. [...] WordPress Auto Login Leon Weblog Posted by root 21 hours ago (http://www.lbsharp.com) How to add auto login functionality to your wordpress site filed under software dev leon 9 31 pm wordpressis a great blogging engine it flexible scalable and easy to btw your comment was not e mailed to me i guess that is on purpose all rights reserved po Discuss  |  Bury |  News | wordpress auto login leon weblog [...]

  22. Hi Leon,

    I’ve been searching for auto-login feature for a week. Thanks a million!

    It works properly but it always login automatically without loggin in.
    In my custom login, I save the username as $_SESSION['uname'] = $rs["usr_name"];.
    Can I change your code as bellow:
    $user_login = $_SESSION['uname'];

    But I still don’t know how to do for registration.
    Thanks again.

    Comment by Wai Wai — May 27, 2009 @ 10:56 pm
  23. After much googling I was beginning to think that it would be better to actually dissect the WordPress libraries. That was, until I found your post!

    My application is a bit different, but this did the trick. Thanks for working hard to make this.

    Comment by Richard Buczynski — June 7, 2009 @ 9:16 am
  24. On a side note, I noticed that you’re from Belarus. I’m from Buffalo, New York, and I have a community of friends from the same area. Great people!

    Comment by Richard Buczynski — June 7, 2009 @ 9:17 am
  25. [...] WordPress Auto Login Leon Weblog Posted by root 9 minutes ago (http://www.lbsharp.com) How to add auto login functionality to your wordpress site comment by rob mcfaul september 24 2008 8 00 am rob save the auto login function in a php file and place it in your all rights reserved powered by wordpress Discuss  |  Bury |  News | WordPress Auto Login Leon Weblog [...]

  26. tq for a useful post

    Comment by AARP — June 27, 2009 @ 7:57 pm
  27. [...] -function reacted differently depending on whether or not a user was logged in or not, so I found the code that automatically logged in a user, which I then added to the top of my PHP-script, and voila, the problem was [...]

  28. I don?t normally comment on blogs but your post was a real call to action. Thank you for a great read, I will be sure to bookmark your site and check in now and again.

    Comment by Micheal Jane — July 2, 2009 @ 1:08 am
  29. worked a treat, cheers!

    Comment by adrock42 — July 24, 2009 @ 2:17 am
  30. Thank you so much.

    I will use it for an open-publishing wordpress version, coming soon.

    Comment by juan — August 11, 2009 @ 1:29 pm
  31. Hi,

    Thanks for the information,just found this post my technorati news feed section! I was searching for this since past 3 months and i am glad to see it here. Thanking you much

    Martin

    Comment by Water ionizer — August 12, 2009 @ 11:31 pm
  32. I want a autologin feature for admin section so that when admin logs in, he gets logged to the blog automatically.

    How to implement this….

    Pls help…

    Comment by Mainak Banerjee — December 24, 2009 @ 12:03 am
  33. Mainak,
    That is exactly what the post explains how to do. You need to create a generic admin account in Wordpress and use the code provided to log a given user in once you determine that the user should have admin privileges.

    Comment by leon — December 25, 2009 @ 6:05 pm
  34. Perfect ! I wanted to realised an open-publishing wordpress site and its exactly what I needed. Thank you so much !

    Comment by yo — January 8, 2010 @ 6:55 pm
  35. A last thing : do you now how to logout automatically on window closing ?

    Detail : I have a popup that redirect to post-new.php with autologin, and I would like to logout on closing this popup. Any idea ?

    Thanks !

    Comment by yo — January 8, 2010 @ 6:58 pm
  36. I wrote an earlier post on managing users in PHP. It may help you with what you are looking to do. Depending on your desired level of security, the session timeout may be good enough as an auto-logout mechanism. See http://www.lbsharp.com/wordpress/index.php/2005/10/13/php-application-framework-design-2-managing-users/

    Comment by leon — January 8, 2010 @ 11:43 pm
  37. Thanks for the information about auto-login feature. Nice blog i like it.

    Comment by Rainbow Skill — January 18, 2010 @ 2:35 am
  38. [...] ???: WordPress Auto-Login | Leon’s Weblog. [...]

    Pingback by WordPress Auto-Login | Leon’s Weblog | ????????? — February 12, 2010 @ 8:34 pm
  39. Hi Leon, Thanks a bunch for putting this together. I have implemented your code and it works like a charm to give registered users in the main site an automatic login to the Wordpress blog as administrator.

    My question is – Can the code be set up to grab each users individual login details and pass that information automatically to the Wordpress login? i.e Jane Doe logs in to the main site and wishes to post on the forum as Jane Doe (as opposed to admin).

    Thank you in advance, you have already done more than enough providing this code and forum. I will keep tinkering but before i start tearing my hair out i thought i would ask the man who engineered the original solution.

    Comment by Paul — February 24, 2010 @ 8:36 am
  40. Paul,

    The least elegant solution to your problem is to simply create a Jane Doe account in Wordpress as well as in your user management system. Using my code you can tell Wordpress which user should be logged in (as long as there is a Wordress account available for that user). A more elegant solution would be to integrate the authentication process so that all users’ credentials will be in the same table. Implementing this, however, is much more involved.

    Good luck, Leon

    Comment by leon — February 24, 2010 @ 10:41 am
  41. Hi Leon, Thanks for the speedy reply =)

    At the moment i have everything running off the one login/authentication table (based off the Wordpress wp_users table); which looks to be where i am running into complications. I will try and separate the login into Site login and Wordpress login and see if i can get the less elegant solution operational while i keep trying to get everything working cleanly off the one login system.

    Although i may have to mimic each user in both tables the solution my be all that is needed for a small user base. I will keep you posted on how things go. Thanks again.

    Comment by Paul — February 24, 2010 @ 9:42 pm
  42. Works beautifully for me with Wordpress2.9. Thanks a lot. BTW, I am planning to make it autologin depending on different current user not just guest or admin account.

    Comment by shallwelin — March 4, 2010 @ 5:28 am
  43. Thank you for this code.

    I would like to be automatically logged in as “admin” et put in functions.php this code :

    function auto_login() {
    if (!is_user_logged_in()) {
    $user_login = ‘admin’;
    $user = get_userdatabylogin($user_login);
    $user_id = $user->ID;
    wp_set_current_user($user_id, $user_login);
    wp_set_auth_cookie($user_id);
    do_action(‘wp_login’, $user_login);
    }
    }
    add_action(‘init’, ‘auto_login’);

    but it doesn’t work. I don’t have any errors, only a blank page.
    It should work no? (wp 2.9.2)

    Comment by Thierry — March 4, 2010 @ 10:16 am
  44. My error is Call to undefined function add_action()

    But this function is used in WP elsewhere…

    Comment by Thierry — March 4, 2010 @ 10:25 am
  45. one problem is that you can’t normally logout by clicking the logout link in wordpress after inserting the code in pluggable.php. when you click back through browser’s go back button after logout, you still can do any action.

    Comment by shallwelin — March 5, 2010 @ 12:42 am
  46. Leon, thank you so much, you saved me hours and hours of frustration!

    Comment by Reine — March 23, 2010 @ 6:13 pm
  47. Can you pull in external script Wordpress user system this way?

    To check if he’s logged in and show something like “Welcome %usersname% ” ?

    I’m noob when it comes to Wordpress coding.

    I see code it’s for auto-loggin, but If I wanna check outside WP if user is logged in in Wordpress…can it be done?

    Thank you!

    Comment by Marius Patrascu — April 23, 2010 @ 7:14 am
  48. Thanks a lot for the piece of code. Got into instant action on my blog.

    Comment by Amol — July 4, 2010 @ 10:34 pm
  49. I just used this (updated) code for a single sign on solution and it worked!! thanks so much, it saved me paying 67$ for a premium plugin because I wanted just that single feature.

    I hooked it into the wp action and modified it a bit to use the user name stored in a session var and woopy-doo, it auto logs on a user if they’ve already logged on to the other site using the same username . wo0t! :-)

    Comment by Andy Bailey — July 10, 2010 @ 1:31 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment