Sunday, 25 September 2016

Login With Google in Java

how to apply OAuth 2.0 in java using Eclipse or Other IDE



Required :

  1. Google Gson Jar File  : Downloal File
  1. Google Developer Account : Create Account

Now Create Account in google developer.



2. Click on Crete Project


3.Give A Name Of Project.


4.Click On Enable API.


5. Select API you want to apply



6. Click On ENABLE



7. Go To Credentials



8. Crete Credentials



9. Create Credentials url



10. Add Project



11. Project Done



Now Create Coding...

  • Open Eclipse or Any Other IDE

  • Create New Web Application in Java


  • Create One page Which Have login Button

Now Create Following Files...

index.html

<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=Your Callback URL&response_type=code&Your Client ID&approval_prompt=force">Sign in with Google
</a>

Note : No any white space allowed..!
  • Now Create java class With Package
  • package Name  "aouth"
  • Class/File Name "Setup.java"

Setup.java

package aouth;

public class Setup
{
public static final String CLIENT_ID = "Your Client ID";
public static final String CLIENT_SECRET = "Your Secret id in You Gson File Which You Download in Console";
public static final String REDIRECT_URL = "Your Callback URL";
}

  • Enter data Which is required..

GlobalCons.java

package aouth;

public class GlobalCons
{
public static String AUTH = "auth";
}


GooglePojo.java

package aouth;

public class GooglePojo
{
 String id;
 String email;
 boolean verified_email;
 String name;
 String given_name;
 String family_name;
 
 public String getId()
 {
   return this.id;
 }
 
 public void setId(String id)
 {
   this.id = id;
 }
 
 public String getEmail()
 {
   return this.email;
 }
 
 public void setEmail(String email)
 {
   this.email = email;
 }
 
 public boolean isVerified_email()
 {
   return this.verified_email;
 }
 
 public void setVerified_email(boolean verified_email)
 {
   this.verified_email = verified_email;
 }
 
 public String getName()
 {
   return this.name;
 }
 
 public void setName(String name)
 {
   this.name = name;
 }
 
 public String getGiven_name()
 {
   return this.given_name;
 }
 
 public void setGiven_name(String given_name)
 {
   this.given_name = given_name;
 }
 
 public String getFamily_name()
 {
   return this.family_name;
 }
 
 public void setFamily_name(String family_name)
 {
   this.family_name = family_name;
 }
 
 public String toString()
 {
   return 
   
     "GooglePojo [id=" + this.id + ", email=" + this.email + ", verified_email=" + this.verified_email + ", name=" + this.name + ", given_name=" + this.given_name + ", family_name=" + this.family_name + "]";
 }
}


GsonUtility.java

package aouth;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonUtility
{
 static String className = "aouth.GsonUtility";
 static Gson gson = new Gson();
 
 public static String tojson(Object object)
 {
   return gson.toJson(object);
 }
 
 public static String getFbAccessTokenFromJson(String j)
 {
   JsonObject json = (JsonObject)new JsonParser().parse(j);
   JsonObject authr = (JsonObject)json.get("authResponse");
   String act = authr.get("access_token").getAsString();
   return act;
 }
 
 public static String getJsonElementString(String name, String gs)
 {
   try
   {
     JsonObject json = (JsonObject)new JsonParser().parse(gs);
     return json.get(name).getAsString();
   }
   catch (Exception localException) {}
   return null;
 }
 
 public static void main(String[] args)
 {
   String s = getJsonElementString(
     "access_token", 
     "{  \"access_token\" : \"ya29.AHES6ZQOuY3Li8MxhD2GOm9E_kaykd0zGAA9x697G7sdHQm5dmwbtA\",  \"token_type\" : \"Bearer\",  \"expires_in\" : 3600,  \"id_token\" : \"eyJhbGciOiJSUzI1NiIsImtpZCI6ImY0MTg2NmE0MTJmZmE5YTFhMDNjYzY5YjY1NDVmZDYzYzM1OGQ0ZDQifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiY2lkIjoiNzMwNjc5MDA1NjcyLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXpwIjoiNzMwNjc5MDA1NjcyLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhZG1pbkBzb2RoYW5hbGlicmFyeS5jb20iLCJ0b2tlbl9oYXNoIjoieDJfbGlLVjdDNm9halJKMF9aQVlFdyIsImF0X2hhc2giOiJ4Ml9saUtWN0M2b2FqUkowX1pBWUV3IiwiYXVkIjoiNzMwNjc5MDA1NjcyLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJzb2RoYW5hbGlicmFyeS5jb20iLCJ2ZXJpZmllZF9lbWFpbCI6InRydWUiLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJpZCI6IjExNDcyOTc2Nzk4Njk3OTU5Nzk1NCIsInN1YiI6IjExNDcyOTc2Nzk4Njk3OTU5Nzk1NCIsImlhdCI6MTM3MDYyNjk1NSwiZXhwIjoxMzcwNjMwODU1fQ.gYBqxfWXmpKIzQDP7AGxGipih5vga1oChKg5YC5OVxwFPpGiXWCwjE46hFq37g0_vdsD93W5lbVPWTr78NqHtUbpQOwOpddATPtjTQt9uXIVG8HrxZwji_5oPYuPpmhFYBfPSLX-08ee9KPfVX3ikn6wTCfe7aR5n-T_Z8-K1IU\"}");
   System.out.println(s);
 }
 
 public static String getElementString(String string, String line1)
 {
   if (line1.indexOf(string) != -1)
   {
     int k = string.length();
     return line1.substring(k + 1, line1.indexOf("&"));
   }
   return line1;
 }

}


OAuth2Callback.java

package aouth;

import com.google.gson.Gson;

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 java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class OAuth2Callback
 */
@WebServlet("/OAuth2Callback")
public class OAuth2Callback extends HttpServlet
{
 private static final long serialVersionUID = 1L;
 static String className = "aouth.Oauth2callback";
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {
   try
   {
     String code = request.getParameter("code");
     String urlParameters = "code=" + 
       code + 
       "&client_id=" + Setup.CLIENT_ID +
       "&client_secret=" + Setup.CLIENT_SECRET + 
       "&redirect_uri=" + Setup.REDIRECT_URL +
       "&grant_type=authorization_code";
     URL url = new URL("https://accounts.google.com/o/oauth2/token");
     URLConnection conn = url.openConnection();
     conn.setDoOutput(true);
     OutputStreamWriter writer = new OutputStreamWriter(
       conn.getOutputStream());
     writer.write(urlParameters);
     writer.flush();
     String line1 = "";
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream()));
     String line;
     while ((line = reader.readLine()) != null)
     {
       line1 = line1 + line;
     }
     String s = GsonUtility.getJsonElementString("access_token", line1);
     
     url = new URL(
       "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + 
       s);
     conn = url.openConnection();
     line1 = "";
     reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream()));
     while ((line = reader.readLine()) != null) {
       line1 = line1 + line;
     }
     GooglePojo data = (GooglePojo)new Gson().fromJson(line1, GooglePojo.class);
     writer.close();
     reader.close();
     request.setAttribute("auth", data);
     request.getRequestDispatcher("/google.jsp").forward(request, response);
   }
   catch (MalformedURLException e)
   {
     e.printStackTrace();
   }
   catch (ProtocolException e)
   {
     e.printStackTrace();
   }
   catch (IOException e)
   {
     e.printStackTrace();
   }
 }
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {}
}

Now All Java File are Created . After then we Display the user's info like as User id, Name, Email ID in pages...

google.jsp

<!DOCTYPE html>
<%@page import="aouth.GlobalCons"%>
<%@page import="aouth.GooglePojo"%>
<html>
<head>
<title>DEMO - Login With Google using Java</title>
<link href='/css/bootstrap.min.css' rel='stylesheet' type='text/css'/>
</head>
<body>

<%GooglePojo gp = (GooglePojo)request.getAttribute(GlobalCons.AUTH); %>
<div style="width:400px;margin:auto;padding-top:30px;">
  <table class="table table-bordered">
    <tr>
      <td>User ID</td>
      <td><%=gp.getId()%></td>
    </tr>
    <tr>
      <td>Name</td>
      <td><%=gp.getName()%></td>
    </tr>
    <tr>
      <td>Email</td>
      <td><%=gp.getEmail()%></td>
    </tr>
    
    
  </table> 
</div>

</body>
</html>

This File Display User information.

After then Run Project.
Thats Done

3 comments:

  1. error HTTP Status 500 - java.lang.NullPointerException ! help me
    !

    ReplyDelete
  2. Which File give an error....????

    ReplyDelete
  3. https://drive.google.com/file/d/0B2KT1a0LW7eNQ2JXTUpEU0FZRFE/view?usp=sharing

    Open this link to get demo

    ReplyDelete