Github is providing OAuth Service. You can implement Github Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Github Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Register App on Github

You can find detail OAuth2 flow on github developers page. First you need to create app in github developer account

Register App On Github

Click here to register you app. Enter required details in the shown form. Here I have registered demo app with name "SodhanaLibrary Demos". You can find sample details in below image.
Don't make "Client Secret Id" public.  Remaining details can be exposed to user

Prepare Login URL

Now you have to provide one URL for user to login with github. That URL should contain client id, redirect url, scope as parameters. Find below for sample URL for sodhanalibrary demo app
https://github.com/login/oauth/authorize?client_id=5338cfe15cb812789cf8&redirect_uri=http://demo.sodhanalibrary.com/oauth2git&scope=user
client_id - Provide your app client id
redirect_uri - Provide your app redirect url
scope - Scope is based on required details of user. Click here to find different scopes
state - It is unguessable string to avoid cross site forgery request attacks. It is optional

Get Access Token

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language.

Get Code value and format URL

Observe below URL. Highlighted words has to be replaced with  your own app details
String code = request.getParameter("code");
URL url = new URL("https://github.com/login/oauth/access_token?client_id="+clientID + "&redirect_uri="+ redirectURI+ "&client_secret=" + clientSecret + "&code=" + code);

Send request for Access Token

URL url = new URL(
        "https://github.com/login/oauth/access_token?client_id="
                + clientID + "&redirect_uri=" + redirectURI
                + "&client_secret=" + clientSecret + "&code=" +
                code);
HttpURLConnection conn = (HttpURLConnection) url
        .openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
String outputString = "";
BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
    outputString = outputString + line;
}
System.out.println(outputString);
String accessToken = null;
if (outputString.indexOf("access_token") != -1) {
    accessToken = outputString.substring(13,
            outputString.indexOf("&"));
}
System.out.println(accessToken);

Get User Details From Acces Token

url = new URL("https://api.github.com/user");
System.out.println(url);

HttpURLConnection myURLConnection = (HttpURLConnection) url
        .openConnection();
myURLConnection.setRequestProperty("Authorization", "token "
        + accessToken);
myURLConnection.setRequestProperty("User-Agent", appName);
myURLConnection.setRequestMethod("GET");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setConnectTimeout(7000);

outputString = "";
reader = new BufferedReader(new InputStreamReader(
        myURLConnection.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString = outputString + line;
}
reader.close();
System.out.println(outputString);
GithubPojo gp = (GithubPojo) new Gson().fromJson(outputString,
        GithubPojo.class);
System.out.println(gp);

Download project

Click here to download project. All code snippets available in this project. Open OAuth2Git.java, and give your github app details over there

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts