Moodle and WordPress Single Sign On in 20 minutes – Part 1

Even if I am a System Administrator, i like to do web things (possibly challenging), and this time, it’s time to make wordpress authentication work on moodle too.

Scenario:
Wordpress installation and Moodle installation.
We are going to use the WordPress database in order to authenticate users within Moodle. Thus, we can sell courses using wordpress ecommerce plugin and have instant access from customers.

The two sites are on the very same machine but on different domains (actually WordPress is in the “www.domain.tld” and “*.domain.tld” subdomains and Moodle is on another subdomain (courses.domain.tld) so we need to authenticate users in both sites using the very same database and table.

The Problem: The Moodle external autentication plugin does not work with WordPress authentication out of the box, instead, it will need a couple of modification very easy to be made, don’t worry, even for a non php skilled person.
We will come back on this later on this post.

Let’s start our 20 minutes modification!

Shop list:

  • WordPress Version 3.4.2
  • WordPress database informations
  • Moodle Version 2.0
  • Moodle External Database Authentication Plugin (already in the Moodle default installation)
  • Some coding so, all stuff for ftp things/sftp/ssh things and a decent text editor with some failsafe feature (save a copy before modify etc)

That’s enough to start working on.

Once installed the two systems, you will have to properly configure the external database authentication plugin on Moodle platform. To do this you have to authenticate yourself as site administrator, then on the menubar choose and click on “Site Administration” -> “Plugin” -> “Authentication” -> “Manage Authentication”.

You can use the provided image on the left to quickly find out the links path needed to get there.

 

 

 

 

 

Once there you will see a list of all authentication plugin, their status (active or inactive) their priority order and their “settings” link.As you can see in the image below, you have to enable and prioritize the plugin in order to make it work. You probably want to disable the self-registration (see picture in bottom part) feature in order to prevent user to signup using moodle platform because, otherwise, all users created within Moodle will not be able to authenticate themselves against WordPress.

This is the list of the moodle authentication plugins. It shows if a plugin is enabled or not, and it exposes a link for each plugin to be configured.

Once you have done, let’s click on the “Setting” link and let’s try to configure this plugin at it best.

We have to enter all info used by Moodle to read the WordPress database.
Fields are:

  • Host, in my case i will use “localhost” and probably you too unless your db is hosted on a different machine, in that case you have to use the Hostname or ip address of that machine
  • Database, in my case “mysqli” (Please, notice the trailer “i” – mysqli and not mysql).
  • Use sybase quotes, we do not need this to be on so we will leave it on “NO
  • Db name, the name of your wordpress database (get it from wp-config.php)
  • Db User, mysql user that can access WordPress db tables
  • Db Password, mysql password for mysql user
  • Table, the name of the table where username/passwords are stored. The most of the time is “wp_users” unless you changed your table prefix
  • Username Field, the field containing the username, for WordPress: “user_login”
  • Password Field the field containing the password for username for WordPress: “user_pass”.
  • Password Format, we should choose “wordpressformat but there is no such option in this drop down, so what? we will solve this later, don’t worry
  • External db encoding, i use “UTF-8″
  • SQL setup command, you can leave it blank
  • Debug ADOdb, choose “NO
  • Password-change URL, we use the wordpress password recovery page link

These are the needed field to make this thing work, if you want more integration, you can configure the part named “cron syncronization script” and sync information such as first name, surname, user preferences and so.

But now we have to stay focused on the missing dropdown item and find a way to get it out of there.

We need to modify the file in /auth/db/config.html and change this (at line 190)

$passtype = array();
$passtype["plaintext"] = get_string("plaintext", "auth");
$passtype["md5"] = get_string("md5", "auth");
$passtype["sha1"] = get_string("sha1", "auth");
$passtype["internal"] = get_string("internal", "auth");
echo html_writer::select($passtype, "passtype", $config->passtype, false);

to this

$passtype = array();
$passtype["plaintext"] = get_string("plaintext", "auth");
$passtype["md5"] = get_string("md5", "auth");
$passtype["sha1"] = get_string("sha1", "auth");
$passtype["internal"] = get_string("internal", "auth");
$passtype["wordpress"] = "wordpress";
echo html_writer::select($passtype, "passtype", $config->passtype, false);

This modification will make “WordPress” authentication drop down item available, but still not working.
We need to process the password with this class: class-phpass.php [Phpass Website].
This class, can actually process passwords the same way wordpress does, so this is the missing link to make sso work.
Just copy the file class-phpass.php in your /moodle/lib folder
And then add this line right after other requires at the beginning of wp-login.php:

require_once($CFG->libdir."/class-phpass.php");

.
To make our modifications work we need to add a few lines of code to the file /auth/db/auth.php, it’s easy. Open the file and go about line 90, you should see something like this:

if ($this->config->;passtype === 'md5') {   // Re-format password accordingly

$extpassword = md5($extpassword);

} else if ($this->config->;passtype === 'sha1') {
$extpassword = sha1($extpassword);
}

 

Now, let’s do our final modification and right after the lines here, add this code:

 

else if ($this->config->passtype === 'wordpress') {
$hash =new PasswordHash(8, false);
$rs = $authdb->Execute("SELECT * FROM {$this->config->table}
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
$check = $hash->CheckPassword( $extpassword, $rs->fields["user_pass"]);
return $check;
}

 

If you are so lazy as i am, you can download a copy of both file here, but i strongly suggest you to make modification by hand because time goes by and releases change.

Moodle auth with wordpress

Now, finally we can come back to the settings page ad add “WordPress” as “Password format“.

All you have to do to try if this works, is to logout from wordpress, signup into wordpress as new user, and then go and authenticate with the same credentials against Moodle. If all work you will be redirected to the user profile page on moodle where you can complete your profile with your informations.

If this article saved hours of your time, you can consider buying me a beer:











 

Incoming search terms:

  • wordpress moodle integration (22)
  • moodle wordpress (19)
  • wordpress moodle (18)
  • moodle wordpress integration (15)
  • moodle single sign on (14)
  • wordpress sso (12)
  • wordpress single sign on (12)
  • wordpress and moodle (11)
  • single sign on moodle (11)
  • wordpress and moodle integration (10)
(Visited 11,335 times, 3 visits today)

41 thoughts on “Moodle and WordPress Single Sign On in 20 minutes – Part 1

  1. Hi Giuseppe,
    Nice concept. Instructions are easy to follow and 20 minutes to set up. However, my setup failed. I did a clean install of both WP and Moodle. Checked both db for user. WP has my user in the db but Moodle db does not. I’m not getting any errors but obviously nothing was coded for that scenario. My db is using localhost as well and all username and pw are correct. Any ideas what might be the problem?

    ~cheers, Matt

    1. Ok,
      First thing i would look at is in the moodle administration, to verify that the choosen method from the dropdown is “WordPress” as it means that modifications made to /auth/db/config.html (at about line 190).
      If you already did it succesfully, you should see the “wordpress” in the password type dropdown.
      If it is so, you can see “wordpress” in the dropdown, but it doesn’t mean it actually works, because you have also to modify /auth/db/auth.php at about line 90 in order to make this works.
      If you already did it but still it does not work, you can temporarely use some short lines of code to debug
      OR
      you can download the attached files (the two with modifications) and try to replace yours.
      My only concern is about the update in moodle released right after my article.
      That’s why if i were you i would check firts these two files against the ones on the new release and possibly we can try to fix it for the newest release too.
      Hope this can really help, and please update about your progress.
      doi doi

    2. Hey Matt, i just found what the problem is. I’t's my fault, i’m sorry, because i missed the entire part about phpass.
      You need it (not within moodle distro) because you cannot process passwords as wordpress does. With this class you will be able to get the SSO.
      Keep in touch

    3. And then add this line right after other requires at the beginning of the file:
      require_once($CFG->libdir.”/class-phpass.php”);

      Where do I have to add this line. In which file and where inside this file “right after other requires”.

      As I see author not checking comments here anymore, so maybe somebody else can help in this case?

      1. Hi i’ve been a little busy with my new job… I don’t usually neglect my blog, it’s just… It has a little hard in last 2 months because I’m working in the Netherlands (I’m Italian) and this is my very first time abroad… Now I’m getting confident day by day (thanks to very nice collegues), so i will be more present on this blog.
        By the way the file you are supposed to paste the require_once statement is “wp-login.php”.
        Sorry i forgot to mention it.
        Ciao

        Giuseppe

  2. Hi Giuseppe,

    First of all thanks for this tutorial, i got it working in under 20 minutes :)

    Was wondering if you were still going to do a second part for this that wouldn’t require a person to login twice, that would be wonderful.

    On a side note the link for phpass was not working but i ended up using this one: http://core.trac.wordpress.org/attachment/ticket/2394/class-phpass.php (probably not the best idea but did the job)

    Again, muchly appreciated!

  3. Hi there,
    I do have the same question like Yousuf:
    In which file do I have to add this require_once($CFG->libdir.”/class-phpass.php”); ?

    Btw the link to Openwall doesn’t link to the correct file anymore :(

    Thank you and best regards,
    Jannis

  4. Hi Giuseppe

    I am having a problem similar to others. Have got the phppass file, but do not know where to insert the line of code, as there are no other requires that I can find in the file …

  5. Hi
    Thanks for the information.

    –> Created all the above steps sucessfully.
    –> All External users are now login with their Exisisting wordpress username & passwords.
    –> but the problem is i am unable to see the users in moodle list of users

    Thanks for the Help in Advance

    1. Did you configure Moodle so external users are imported as well?
      Some time has past but i can remember that somewhere i had to map wordpress user fields with moodle user fields, thus as soon as a new user logon on moodle checking credentials against wordpress database his data are transfered on moodle db…
      I’ll take a look and I’ll let you know.

  6. Great post Giuseppe, going to give this a try later today i think. Any plans to create the second post you mention?

    I’m very surprised that a plugin for WP/Moodle hasn’t been developed for this yet. I’ve used Moodle and Joomla together using Joomdle (http://www.joomdle.com) – I’d love to see a similar plugin or WP!

    1. Hi, i honestly don’t know if and when i’ll do it. I think that my approach wasn’t correct.. I mean it works until now, but maybe it would have been better to think at ldap…
      What do yuo think?
      Could it be a solution? I’m pretty sure there is something for both wordpress and moodle so they can be used with ldap…

  7. Hi and thanks for your help.

    I found the class-phpass.php on the web
    Then I copied to /moodle/lib folder

    But my problem is the next step:

    And then add this line right after other requires at the beginning of the file:
    require_once($CFG->libdir.”/class-phpass.php”);

    Where do I have to add this line. In which file and where inside this file “right after other requires”.

    Regards,

    Fernando.

  8. Hi!
    When I put the line require_once($CFG->libdir.”/class-phpass.php”); on my wp-login.php file, it shows this error:

    Warning: require_once(/class-phpass.php) [function.require-once]: failed to open stream: No such file or directory in /home/storage/b/5f/4a/site13670345/public_html/curso/wp-login.php on line 12

    Fatal error: require_once() [function.require]: Failed opening required ‘/class-phpass.php’ (include_path=’.:/usr/share/pear’) in /home/storage/b/5f/4a/site13670345/public_html/curso/wp-login.php on line 12

    Do you know what could had happened?

    Tks so much,
    Andrea

    1. It looks like you’re missing the file in that location. Personally i took a quick look at mine and i have:
      require_once( ABSPATH . ‘wp-includes/class-phpass.php’ );

      As you can see i have “ABSPATH . ‘wp-includes/” in place of $CFG->libdir.blah
      If I’m not wrong an update in wordpress messed my post right after a couple of day after i wrote it.

      In a few words: try as I did. Let me know.

      Giuseppe

    1. Actually,

      All sorted, just copied the file from an old version of WordPress I had here locally :)

      Cheers,
      Dan

  9. Hey Giuseppe,

    Great work. But shouldn’t the following line:

    And then add this line right after other requires at the beginning of wp-login.php:

    Read as:

    And then add this line right after other requires at the beginning of lib/db/auth.php:

    Cheers,
    Dan

  10. Hey giuseppe,

    Great Work..!!

    I have a question –
    Can we do the same in vice versa – using the moodle database, authenticate users in wordpress., If so need the procedure for doing it.

    Also, waiting for the SSO too…!!

    1. I can’t tell right now, as it i hard to remember details, but when i started i was 100%free and if i went this way there has been one reason. Probably the other way around is harder than this.

  11. Excellent step-by-step guide, but I noticed a typo I think. In the section on adding the required “class-phpass.php” authentication class, you said to make the change in “wp-login.php”. I think that should instead read “auth.php” since we’re adding the WordPress authentication class within Moodle, not making any changes to WordPress itself. If you have trouble finding the “class-phpass.php” on http://www.openwall.com/phpass/ its because that project recently changed their site structure (old download links may be dead and the authentication class is now called “PasswordHash.php”), but to be sure you’re using the same version as WordPress, just copy and paste the code from “wp-includes/class-phpass.php” that way you can be sure you’re using the same auth code).

    The other little thing was that in the latest version of Moodle, the addition of the “else if” statement to catch “wordpress” logins should be placed on line 113 instead of line 90.

    Anyway, those little changes aside, it worked for me as of latest versions of both WordPress and Moodle in October 2013 so thanks a bunch!

    Lastly, I noticed this article is labelled as “Part 1″, is there a Part 2 on “automatically logging in using your now synched-up login credentials” to have it so that a login activity in WordPress automatically fires a login action to Moodle?

    If it exists or if you can make one, a several beer donation is indeed headed your way!!! I’m just not sure if its possible to automate that (maybe hidden Moodle form field added to “wp-login.php” with Javascript auto-fill of values and asynch POST)?

    1. Hey BSC, I followed your small changes and I still can’t this to work. Not sure why I’m having trouble. Any thoughts?

  12. Hey there, I have tried to implement this, but having trouble with the

    require_once($CFG->libdir.’/class-phpass.php’);

    as soon as I input this line into auth.php I get white screen when trying to access the login page. I’ve followed the other steps to the T, but seems this step is giving me issues and not sure what to do.

    -L

    1. Hi, white page means that you are not showing errors. try to check logs, and see. It usually is a typo or something similar. You are just not seeing the error.

  13. I have been searching for this kind of data for a long time, but I was struggling
    to get a dependable source so far. Thx.

  14. Hi Giuseppe,

    Thanks a lot for the post. It worked (not form the first time but it did).

    Unfortunately it hasn’t solved my problem as I need to send users to moodle via log in form in wordpress. For now my users have to log in twice while the idea is:

    1. log in via wp only
    2. redirect logged-in user straight to moodle (user is not supposed to see wp user panel)

    Could you suggest any solution?

    Thanks a lot in advance.

    Valeria.

    1. Hi Valeria, i have few minutes right now, but let’s say that: since i wrote that code a lot of time has passed but at same time i see the topic is still kind of “warm” not to say “hot”.
      Plus i received some request/donation for this.
      So i was thinking to start a somehow “official” project on git or google code in order to maintain it through wp and moodle updates. Next weekend I’ll start gathering all the pieces and we will figure out a way to make it work (at least on the wp side) like a plugin, creating some menu to control options like your point 2.
      That will make us cooperate as normally happens in free software environment, keep the code up to date, and make easy for non tech people to use it as well.
      I’ll update the post with this info. You should receive an email then so we could start working together with all others involved into this.
      Giuseppe ;)

      1. Hi Giuseppe,

        Happy to hear that. :)

        I found a temporal solution, added a login form into WP that brings user directly in Moodle right after logging-in. Also I changed the email that WP sends to the user after registration adding there a link to that special login page in WP.

        Obviously, these changes are going to dissapear after new WP update. So to have a plugin that does all the job and does it better would be super cool for all who use WP and Moodle. :)

        1. Nice! Yes you got the point: make changes survive to wp updates. That’s achievable with making it work as plugin.
          Anyway as said, let’s see this weekend what can be done this way
          Giuseppe

  15. Hi Jeff,
    i will publish step 2 soon. Have to figure out the best way, but the first step is to ensure that both subdomain can access eachother cookie.
    In the meanwhile, if you have some problem, feel free to write me.

Leave a Reply to Andrea Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>