Introduction
Today I embarked on a journey to learn about all the major social login providers. Starting with GitHub. This is also part of my making of OpenAuth's social logins. Alright, so let's start without any further ado.
GitHub OAuth Flow
$$ Application \xrightarrow{Redirects User} GitHub \xrightarrow{Returns Identity} Application \xrightarrow{Fetch Access Token} GitHub $$
Now with this access token, we(the application) can send requests to the GitHub API and get data about the user.
Coding this is also pretty simple as GitHub is one of the simplest and easiest social login flows.
Setting up
There are some things we need to set up before we can implement the OAuth flow.
- A GitHub OAuth App
Setting this up is pretty simple, just head on over to Developer Settings in GitHub and register a new application, and fill in the details. You can provide any name, description, and homepage URL. The callback URL is the URL to which GitHub will redirect the user once they have been authorized. This needs to be carefully selected. The callback URL for development purposes should be something like http://localhost:PORT
where PORT
is the port at which your app is running. This URL should be changed to the URL of your website when it is in production.
Alright, now that that's done, let's start implementing it.
Implementation
Implementing the GitHub OAuth is as simple as just making 2 HTTP requests.
The Requests
GET https://github.com/login/oauth/authorize?client_id=XXXXX&redirect_uri=XXXX&scopes=XX XX XX
Here, the client_id
is found when creating the GitHub OAuth app from the above step, redirect_uri
will be the URL provided as the callback URL, and scopes
will be a list of space(" ") separated scopes. You can find a list of all the scopes available here. scopes
is optional.
The above request, responds with a temporary code. We will need this code to change for the access token.
POST https://github.com/login/oauth/access_token?client_id=XXXXX&client_secret=XXXXX&code=XXXX
Now using the code
from request 1, and client_secret
from the GitHub OAuth App, we can get the access token by simply parsing the JSON data returned.
Accessing User Data
Now with this access_token
you can get the user's data from the GitHub API by setting the Authorization
header in the request like this: Authorization: token access_token
. You can have a look at the GitHub API Documentation for more info.
That's all
See you in the next article!