Google is providing OAuth Service. You can implement Google 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. Google 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 

Get OAuth 2.0  Credentials from Google developer console 

  1. Go to Google Developer Console
  2. Create Project and Open that project
  3. Go to API & Auth > Credentials > Create New Client ID. Here one new dialog box will open and show some options. Now select web application, Give you website URL (example: http://demo.sodhanalibrary.com) in JavaScript origins and Give redirect URL (example: http://demo.sodhanalibrary.com/oauth2callback). Now click on Create Client ID button.
  4. Now you can see your client id and client secret id.

Sample Project

Click here to download the eclipse project. Open Setup.java and enter app details, Open index.html and format login URL with your own app details

Form the URL

Now we need to create a button with Auth URL. Syntax of the URL is
https://accounts.google.com/o/oauth2/auth?[parameters]

Some important Query Paramenters

  1. client_id: Which you got at Google developer console
  2. response_id: For web application response_id is code
  3. redirect_uri: Redirect URI which you given at Google developer console
  4. scope: to get profile info give profile as scope, to get email address give email as scope
  5. approval_prompt: (force or auto) If it is force, user must accept to your scope or else it will be optional.

The Auth URL get Users Email Address

 https://accounts.google.com/o/oauth2/auth?
 scope=email&
 redirect_uri=http://demo.sodhanalibrary.com/oauth2callback&
 response_type=code&
 client_id=your application client id&
 approval_prompt=force

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 Parameters

String code = request.getParameter("code");
String urlParameters = "code="
                    + code
                    + "&client_id=Your app client id"
                    + "&client_secret=Your app secret id"
                    + "&redirect_uri=http://demo.sodhanalibrary.com/oauth2callback"
                    + "&grant_type=authorization_code";
Now we have to send that code with client id and secret id to https://accounts.google.com/o/oauth2/token

Java code to post parameters

URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();

Extract Access Token

After posting above parameters to Google Auth URL, we will get response which contains Access Token. Now extract that access token from that response.
JsonObject json = (JsonObject)new JsonParser().parse(line1);
String access_token = json.get("access_token").getAsString();

Get User Info

Now we have access token so we can get user info.
url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
        outputString += line;
}
In the above code outputString contains the User Info

User info in JSON format

  {
    "id":"user id here",
    "email":"email here",
    "name":"name here",
    "given_name":"given name here", 
    "family_name":"family name here"  
  }

POJO Class to handle JSON rensponse

public class GooglePojo {
    String id;
    String email;
    boolean verified_email;
    String name;
    String given_name;
    String family_name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isVerified_email() {
        return verified_email;
    }

    public void setVerified_email(boolean verified_email) {
        this.verified_email = verified_email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGiven_name() {
        return given_name;
    }

    public void setGiven_name(String given_name) {
        this.given_name = given_name;
    }

    public String getFamily_name() {
        return family_name;
    }

    public void setFamily_name(String family_name) {
        this.family_name = family_name;
    }

    @Override
    public String toString() {
        return "GooglePojo [id=" + id + ", email=" + email
                + ", verified_email=" + verified_email + ", name=" + name
                + ", given_name=" + given_name + ", family_name=" + family_name
                + "]";
    }
}

Whole Servlet Code 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Oauth2callback extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Oauth2callback() {
        super();
        
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("entering doGet");
        try {
            // get code
            String code = request.getParameter("code");
            // format parameters to post
            String urlParameters = "code="
                    + code
                    + "&client_id=Your App Client ID"
                    + "&client_secret=Your App secret client ID"
                    + "&redirect_uri=Your App Redirect URL"
                    + "&grant_type=authorization_code";
            
            //post parameters
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            URLConnection urlConn = url.openConnection();
            urlConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(
                    urlConn.getOutputStream());
            writer.write(urlParameters);
            writer.flush();
            
            //get output in outputString 
            String line, outputString = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            //get Access Token 
            JsonObject json = (JsonObject)new JsonParser().parse(outputString);
            String access_token = json.get("access_token").getAsString();
            System.out.println(access_token);

            //get User Info 
            url = new URL(
                    "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
                            + access_token);
            urlConn = url.openConnection();
            outputString = "";
            reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            // Convert JSON response into Pojo class
            GooglePojo data = new Gson().fromJson(outputString, GooglePojo.class);
            System.out.println(data);
            writer.close();
            reader.close();
            
        } catch (MalformedURLException e) {
            System.out.println( e);
        } catch (ProtocolException e) {
            System.out.println( e);
        } catch (IOException e) {
            System.out.println( e);
        }
        System.out.println("leaving doGet");
    }

}

42 comments:

  1. is your server supports java?

    ReplyDelete
  2. Can you please share the WAR file? It will be really help full to deploy and test?

    Thanks

    ReplyDelete
    Replies
    1. Shared the project, please download it

      Delete
  3. after getting access token i am unable to get the user info

    ReplyDelete
  4. Hi Srini , I am not able to see the google page even after i hit the submit button. can you let me know what is the issue

    ReplyDelete
  5. I am getting the same error. Please explain

    entering doGet
    java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
    leaving doGet

    ReplyDelete
  6. Hi,

    please share your file, it will be helpful

    ReplyDelete
    Replies
    1. Shared the project, please download it

      Delete
  7. please share the project Srinivas.

    ReplyDelete
    Replies
    1. http://downloads.sodhanalibrary.com/download?id=11

      U need to subscribe to download it

      Delete
  8. Hello Dasari, i registed my e-mail by http://downloads.sodhanalibrary.com/download?id=11, but i can't download it.

    ReplyDelete
  9. Hi... Which Libraries are required ....????

    ReplyDelete
    Replies
    1. no special libraries needed, just google-gson (https://github.com/google/gson) is enough

      Delete
  10. hi! if i have done my site whit tomcat, can i do this tutorial?
    because in JavaScript origins and Give redirect URL i have localhost../nameProject and google don't accept this. please reply.
    if i can't do this, how do i do?

    ReplyDelete
    Replies
    1. Go to Google developer console, add your localhost url under "Authorized redirect URIs"

      Delete
  11. hi srinivas I had downloaded the war and trying to run from my local system and I had followed the above steps mentioned I able to get the code but while trying to get the access token I am facing the problem of (SSLHandShake Exception) is any thing more to be configured if needed kindly guide me and the error is occured at the line (OutputStreamWriter writer = new OutputStreamWriter(
    conn.getOutputStream());

    ReplyDelete
    Replies
    1. This is due to HTTPS (SSL Certificate), this might help you http://blog.sodhanalibrary.com/2015/12/how-to-solve-javaxnetsslsslhandshakeexc.html#.WD_LtqJ95hE

      Delete
  12. Sir when my web page redirect then some error:

    error is

    HTTP Status 404 - /OAuth2Callback

    type Status report

    message /OAuth2Callback

    description The requested resource is not available.
    Apache Tomcat/8.0.36


    my web page url is http://sumit.ap-south-1.elasticbeanstalk.com

    ReplyDelete
    Replies
    1. Check your web.xml configuration

      Delete
    2. java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token

      how to solve this error

      Delete
    3. Its bad request, It means you are not following rules of Google auth. Check urlParameters that you are sending to https://accounts.google.com/o/oauth2/token

      Delete
  13. Hello Srinivas Dasari,

    There is something wrong with download functionality : "http://downloads.sodhanalibrary.com/download?id=11".

    I already have subscribed [24+:hr], but showing this : "Your email (*mail@mail.com) is not in our subscribed email list"

    Tried to subscribe again, but now showing this : "*mail@mail.com is already subscribed to the mailing list of SodhanaLibrary".

    Looks like deadlock.

    ReplyDelete
    Replies
    1. From last 2 days, the server didnt update properly. sorry for the inconvenience, Now its working fine. Make sure that your feedburner subscription verified

      Delete
  14. Hello Srinivas Dasari,
    java.io.IOException: Server returned HTTP response code: 401 for URL: https://accounts.google.com/o/oauth2/token
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)

    how to solve this error

    ReplyDelete
    Replies
    1. 401 error means unauthorised access. Check client_id and client_secret in urlParameters

      Delete
  15. Hello Srinivas Dasari,
    nothing wrong in client id and client_secret.I wrote redirect url like(http://localhost:8080/GoogleAuth/oauth2callback) here GoogleAuth is my project name.Is this valid or not??

    ReplyDelete
    Replies
    1. You should add that URL in Google developer console app settings

      Delete
  16. sir getting error
    Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token

    Please help... where is there error can you tell me

    ReplyDelete
  17. I am getting the same error. Please explain

    entering doGet
    java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
    leaving doGet please help me

    ReplyDelete
  18. I have an error "HTTP Status 500 - java.lang.NullPointerException" ! help me

    ReplyDelete
  19. sir can you give me the netbeans realated project

    ReplyDelete
  20. hello,
    when i try to run your code using my app id and redirect uri, i am getting a blank screen in response(oauth2callback). can u please tell me the reason for it???

    ReplyDelete
  21. hiii, i am trying with this code but it is showing a error of javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)


    and
    java.lang.NoClassDefFoundError: Could not initialize class com.javapapers.java.social.Google.GsonUtility
    com.javapapers.java.social.Google.OAuth2Callback.doGet(OAuth2Callback.java:58)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    ReplyDelete
  22. I have created new project on Google Developer Console with below details:

    public static final String CLIENT_ID = "697584815978-k8d8lm334gco5o01773cffe0lq3t1cvb.apps.googleusercontent.com";
    public static final String CLIENT_SECRET = "_EzSu0M80LXL6m3XTDoCufmU";
    public static final String REDIRECT_URL = "http://localhost:8080/GoogleLoginDemo";

    The Auth URL get Users Email Address is below:
    https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://demo.darshanlibrary.com/oauth2callback&response_type=code&client_id=697584815978-k8d8lm334gco5o01773cffe0lq3t1cvb.apps.googleusercontent.com&approval_prompt=force

    After this, i am getting "Allow" option on explorer page, when i click on ALoow:

    Getting below token:
    http://demo.darshanlibrary.com/oauth2callback?code=4/AAAzk7MLfUcfkVMJtis8f0brVs8edUC4e631s1Hm1O_R6UfDiWh1frMx8yDgHKmn-cOvnXDjkLv7bw5v5bpQQ4s#

    This page can’t be displayed

    •Make sure the web address http://demo.darshanlibrary.com is correct.
    •Look for the page with your search engine.
    •Refresh the page in a few minutes.


    Please let me know what i am doing wrong?

    ReplyDelete
  23. I am hoping the same best effort from you in the future as well. In fact your creative writing skills has inspired me. Buy Google Places Reviews,

    ReplyDelete
  24. I found your this post while searching for some related information on blog search Its a good post. สมัครสมาชิก 123betting

    ReplyDelete
  25. Extremely useful information specifically the ultimate section I handle such info much. virx สเปรย์พ่นจมูก

    ReplyDelete

Blogroll

Popular Posts