Connect Drupal 7 and Github via Oauth

In a project where I am working on there is a need to connect Drupal with Github.

Github offers an interesting API which is based on the Oauth protocol like Google and Twitter.

The first thing to do is creating an account on Github and on the profile page add an application url even setup in localhost (like http://localhost/drupal). When done, you will receive a client id and a client secret which will be used by Drupal to connect as client.

I setup Drupal on my laptop via Xampp, which means creating quickly a user “drupal” with a database “drupal” via phpmyadmin and then extract Drupal in my htdocs folder (using drupal as folder name) and follow the instructions at http://localhost/drupal.

On Drupal you need download and setup the Oauth connector module which comes with some dependencies, in particular the Oauth module which can be used for Oauth2.

Once everything is setup you can start to configure and for this you can follow the steps in this guide for  Facebook:

http://fuseinteractive.ca/blog/how-allow-facebook-logins-your-drupal-site#.VRwyEjuUdLZ

with the data used from here (I just forked the original project):

https://github.com/EmidioStani/drupal-oauthconnector-providers/blob/master/GitHub.php

as you can see there is a mapping to be done between the github profile attributes and the drupal profile attributes. Since the Github name attribute is optional I preferred to use the login attribute (you can see some attributes from my profile), so just change it in:

'name' => array(
'resource' => 'https://api.github.com/user',
'method post' => 0,
'field' => 'login',
'querypath' => FALSE,
'sync_with_field' => 'name',
),

Unfortunately the avatar will not be copied but you can contribute to the module :-)

When you will connect to Github you might experience 2 types of problem:

If everything goes fine, at the end you will have a github button at the login which redirect the user to Github and come back to Drupal.

Be careful that when you come back to Drupal you have a session cookie therefore the new user is authorized but, since Drupal by default blocks the user (because by default the administrator should authorize and the account should be confirmed by email), you cannot login with your account; also my Drupal doesn’t send emails. So I suggest to remove the cookie from your browser, login with the administrator and unblock the user (you will be able to login with the github account) and change the options in Drupal to allow people registering automatically without waiting that the administrator unblocks the user.

With the last changes you would expose Drupal to security issue but I didn’t try it a Drupal hosted on a website and with email confirmation.