Skip to content


WordPress Authentication via Google Apps

While working on a new WordPress-based website for Drexel Smart House (DSH) today, I wanted to provide an easy single-sign-on (SSO) solution for DSH members. DSH already uses Google Apps for everything, so why not use their Google Apps emails to login to WordPress as well? Should be easy, right?

I found a couple of ways to do this… the first, and seemingly easiest, is by using the RPX plugin from Jan Rain. However, I didn’t want to even offer the option to users of choosing among Facebook, Twitter, Google, MySpace, Yahoo, OpenID, and more to login. I wanted a simple, familiar username/password box that only accepted @drexelsmarthouse.com accounts and verified the password with Google Apps.

The second way, and the one DSH is using, is a creatively named plugin called 3rd-Party-Authentication. It allows the administrator to configure any POP3 or IMAP based email to be used for authentication; as a bonus, it has Google Apps, Gmail, and GoogleMail accounts pre-configured. So if all you want is Google Apps authentication, just enter your domain name. Easy!

Plus, its pretty configurable; the admin can easily select the Google Apps domains and custom email (POP3/IMAP) domains to be allowed, as well as specifying whether Gmail and GoogleMail are allowed. It even offers to auto-create new users from the allowed domains for you!

Plus, the interface is exactly what I wanted, i.e., nothing out of the ordinary.

It even has built-in user instructions. Perfect!

The problems come when trying to get it to work. This little beauty has almost zero documentation or tutorials online. This is where I come in :-)

Like most of you reading this tutorial, I expect, I was getting very frustrated when it didn’t appear to be working. After reading the sparse comments scattered about the web, I had my first a-ha! moment.

Secret #1: your username has to be your Google Apps (or IMAP/POP3) email.

The plugin doesn’t match logins to WordPress users based upon their email field, as you (and I) probably expect(ed). So, after installing the WPVN Username Changer plugin, I changed my username to my @drexelsmarthouse.com email address. After changing the password stored in WordPress to a random string (to avoid a false success if both passwords happened to be the same), I tried to login again.  Success!

Next, I didn’t want to add WordPress user creation to my IT workflow, so I enabled auto-creation of users. I tried it out on one of our Google Apps test accounts, and it worked! But not so fast… I had one of my friends in DSH test it out to see if it worked for him… and of course it didn’t. Instead, it displayed the uber-informative error message “Invalid username”.

<mumbles>stupid plugin made me look like a fool.</mumbles>

So I set about trying to figure out the issue; thankfully, my friend let me change his Google Apps password so I could debug the issue on his account, repeatedly simulating (i.e., causing exactly) the failure while stepping through the code one line at a time and watching the wp_users table in the database. (I originally suspected an issue with the dot in his username/email for some reason.)

Eventually, I found out the error message was completely wrong. What was actually happening had nothing to do with the username, but rather the user’s email address. The user was not being added; the wp_create_user function was returning the error ‘This email address is already registered.” But he wasn’t registered in the wp_users table. So… How?

Secret #2: The plugin was auto-creating users with an empty email address (empty-string: ”).

The first auto-created user succeeded, creating the user without an email address (as the secret says). The second auto-created user also tried to use an empty email, but it was already taken by the first user. Emails aren’t being correctly set/stored. There’s the problem.

I’ve already alerted the plugin author of this issue, and hopefully it will be patched in the next minor release. In the meantime, you can just change one line in the code yourself to make it work. Open up the Plugins > Editor SubPanel to the file 3rd-party-authentication/3rd-party-authentication.php.

Inside the login_failed() method, update the call to wp_create_user from

$user_id = wp_create_user( $username, $random_password, '');

to

$user_id = wp_create_user( $username, $random_password, $username );

That’s it!

There is a repercussion for people who care, though. Namely, this is terrible in terms of database normalization; changing your email address does not change your username, and thus you could end up signing in with a different email address than that used by WordPress (and displayed on your author profile). This could be confusing to users…

Regardless, thanks to James David Low for creating this nifty little plugin.

UPDATE: If you get tired of seeing the “ERROR: The username field is empty” on the initial load of your login page, there is an easy fix. In the same file (3rd-party-authentication/3rd-party-authentication.php), simply replace

	if ( '' == $username )
		return new WP_Error('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
 
	if ( '' == $password )
		return new WP_Error('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));

with the following:

	if ( '' == $username || '' == $password)
		return new WP_Error();

Posted in Tutorials.


33 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Glen says

    Thanks for the info. I was having trouble with the 3rd Party Authentication plugin while trying to create an intranet site for our schools. We use Google Apps for Education and I didn’t want to create another login for our staff, this was an excellent solution but was tricky to get setup correctly and not lock myself out of the site.

  2. chaggui says

    Hi

    Great plugin. Like it. I just have a problem to connect with gmail.com account.

    I try with xxxxx@gmail.com, user is automaticly created, but error message is displayed about ssl. It is not available on my webserver. I used a free.fr webhosting account.

    It is possible to deactivate this security ?

    Error message is : "Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://www.google.com:443 (Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?) in /mnt/148/sdb/8/9/MyAccount/wp2/wp-content/plugins/3rd-party-authentication/httplib.php on line 111

    Warning: fwrite(): supplied argument is not a valid stream resource in /mnt/148/sdb/8/9/MyAccount/wp2/wp-content/plugins/3rd-party-authentication/httplib.php on line 112

    Warning: fclose(): supplied argument is not a valid stream resource in /mnt/148/sdb/8/9/MyAccount/wp2/wp-content/plugins/3rd-party-authentication/httplib.php on line 116"

    • codyaray says

      I’m afraid that Google requires SSL for authentication, otherwise your password would be sent across the network unencrypted. Without SSL, it would be extremely easy for others to intercept your login info and then hack your account. You’ll have to look into enabling SSL on your web host or switch providers. (Depending on your host’s setup, it might be something that can be enabled through an .htaccess file. Google it.)

  3. Dominic Morrocco says

    Codyaray,

    This is a fantastic solution for SSO with Google Apps. I’m looking forward to implementing this along with Genesis & InfusionSoft for our intranet that I am working on.

    Thank you very much,
    Dominic

    • codyaray says

      Thanks, Dominic! I’m glad it helps you.

      What are Genesis & InfusionSoft? Google suggests the “Genesis Health System”? (That’s the only Genesis intranet I can find; others are Biblical or rock bands.) And InfusionSoft appears to be a (fairly expensive) Email Marketing Automation system. Why such an expensive solution when so many much lower-cost competitors exist (unless you are indeed in the healthcare biz and InfusionSoft meets some non-obvious [to me] HIPAA requirements?).

      I’m always looking to learn. :-)

  4. Dominic Morrocco says

    Cody,

    Would it be difficult to extend this plugin so when a user is logged into WordPress via their Google Apps credentials, they don’t have to re-login with the Google App credentials should they click an Apps ink in WordPress for Email, Calendar or Contacts?

    -D

    • codyaray says

      I believe this plugin uses POP/IMAP (email) authentication under the hood, so it wouldn’t be an easy matter to extend for such functionality. In general this form of “true” SSO is difficult to achieve with multiple/distributed apps (e.g., WordPress, Google Apps, etc). OpenID provides a standardized SSO that uses a 3rd party engine to handle all authentication calls, bypassing the technical difficulties inherent in most SSO solutions**. I know Google Apps can provide OpenIDs for Users, but I’m not sure if the JanRain WordPress plugin (or any other plugin, for that matter) provides the functionality for which you’re looking.

      ** Generalizing a lot and without getting into too many technical details, most apps authenticate users by storing some info in a client-side cookie (i.e., data stored in your browser), which usually contains some (often encrypted) key to lookup the user’s data on the server (see PHP’s sessions or any number of Ruby on Rails’ auth plugins for details). However, for security purposes, websites (e.g., Google Apps) can only read cookies that they set themselves, making an immediate and obvious solution to having WordPress set an authentication cookie and Google Apps read it (or the reverse) a non-trivial matter.

  5. Té says

    Is there any way to have this plugin retrieve and store information such as the user’s full name? I am not sure if that can be sent over POP / IMAP

    • codyaray says

      I don’t believe there’s any functionality in the POP3/IMAP protocols to allow for such an exchange. However, users can set their own names in their WordPress profile after signing on, so I don’t consider this a great loss (for my needs). If you really need pre-populated registration fields, you might checkout OpenID, which has a simple registration extension including such functionality. Google offers OpenID logon as well.

  6. Fsherratt says

    Is there any way to stop this plugin generating accounts for users that don’t exist on the google apps database?

    • codyaray says

      Never even realized this was a problem, but after testing on my own setup, I see what you mean… when you try to login with a bogus username@yourdomain.com, it creates it as a user. That’s annoying. It hasn’t been an issue for me yet, obviously, but you should report this as a bug to the plugin author. He was pretty fast at incorporating my bug fixes, so hopefully it’ll be the same. You can find his info/link at the bottom of my post. Let me know how it goes!

  7. Josin says

    Thanks for your ‘tutorial’, the plugin worked fine. Now I have a question. How can I modify the installation so that users won’t have to enter the whole email ID, but just the part before the @ symbol.

    (Eg: If a user email is mathew@stjohns.ac.in, he must have to enter just ‘mathew’ and not just the whole email)

    • codyaray says

      If there’s only one email domain that you want to support, it would be easy to modify the source code so that it automatically appends the domain to whatever is entered, but that might break other functionality in the plugin. Go ahead and try it. I’d love to hear how it works out for you. :)

  8. Josin says

    After installing the plugin, when i tried to login as ‘admin’ it showed and error “username not an email”, and I couldn’t login. Any solution?

    • codyaray says

      Make sure you enable “Allow regular logins? (Allow regular logins as well as email/google logins?)” in the plugin options screen as well. Works for me.

      • greg says

        And how do I do that post-locking myself out because its not accepting my admin or my google apps login?

        • greg says

          nm…

          update wp_options set option_value = 1 where option_name = ‘3rd_party_allow_regular';

          • codyaray says

            I’m glad you figured it out, Greg.. and thanks for sharing this tip with everyone else! :)

  9. whall says

    Wow, great article. Love it when people dive into issues like this and document it for others. I’m looking forward to giving this a try on our wordpress site (nonprofit band boosters). I already have Facebook integration working, but we use Google Apps for our back-end stuff and letting the board members use that to login to wordpress and submit articles would be wonderful.

  10. qsito says

    I’m receiving a “Domain not supported” error when I try to sign in… any suggestions?

    • qsito says

      nevermind, fixed… stupid typo, thanks anyway!

      • codyaray says

        Well, glad to help :)

  11. Marco Matarazzo says

    Great article, it was a great time-saver. Thanks !!!

  12. Martin says

    Hello. Great article by the way.
    I’m having a weird problem and I can’t figure out how to fix it. I had the regular WP admin user, and then a bunch of @mydomain users using this plugin, then one day, suddenly I wasn’t able to login with regular admin any more (username not am email).
    I now… I read the post about this error, BUT, the solution given doesn’t work for me…
    I’m lucky to have another account with admin rights so I can login and change things around. I got regular logins enabled, checked that value “1” in wp-options but I’m still getting that message.
    Any ideas?

    THANKS

    • codyaray says

      On your login page, does it say something about using your WordPress email to login? If it just says something about your @mydomain email, then its not configured correctly to use regular logins. (There may be other options available that need checked. By “wp-options” do you mean a config page in the UI or in the database? I haven’t really had to touch this stuff since I wrote this post.)

  13. Andrew Kneebone says

    I feel that I am close… but

    when i login in the page waits about 10 seconds, creates the user but doesn’t let me through. Now the wordpress site has the user registered but it still doesn’t let me in stating incorrect password :(

  14. Christie says

    Hi, just wanted to say, I loved this blog post. It was inspiring.
    Keep on posting!

  15. Ram says

    Sweet stuff. Looks like the plugin folks fixed the empty username issue already.

  16. Dan Lester says

    This article really helped me, but I also came to realize things have changed since it was written.

    Especially for HTTP-only sites, I feel uncomfortable with my genuine email password being submitted to a blog. It’s one thing for the blog account to be hacked, but then losing access to my email is too big a risk.

    OAuth2 is now preferred over OpenID by Google, so I have built a plugin to easily sign on to WordPress via Google accounts – including Multi-factor Auth if enabled. This saves entering a password directly to WordPress at all.

    I hope you don’t mind me sharing it here, and of course I welcome any feedback:

    http://wordpress.org/plugins/google-apps-login/

    Thanks,

    Dan

  17. eduardo says

    ya no funciona la conexion alguna solucion???

Continuing the Discussion

  1. james david low / work / 3rd Party Authentication linked to this post on October 1, 2010

    […] 0.2.3 Fix so auto creating users populates email field allowing more than on user to be created! Thanks Cody! 0.2.2 Added text on login page to indicated regular logins work 0.2.1 Bug fix for when using […]



Some HTML is OK

or, reply to this post via trackback.

 



Log in here!