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
- User will click on Auth login link
- Google Auth server will show permission screen to user
- Once user accepts to the scope, It will send code to App Server ( Redirect URI)
- Once we got code, get access token by using client secret id
- Access User's Information using that access token
Get OAuth 2.0 Credentials from Google developer console
- Go to Google Developer Console
- Create Project and Open that project
- 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.
- 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
- client_id: Which you got at Google developer console
- response_id: For web application response_id is code
- redirect_uri: Redirect URI which you given at Google developer console
- scope: to get profile info give profile as scope, to get email address give email as scope
- 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";
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; }
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"); } }
is your server supports java?
ReplyDeleteYes...Its on Google App Engine
DeleteMachine Learning Projects for Final Year machine learning projects for final year
DeleteDeep Learning Projects assist final year students with improving your applied Deep Learning skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include Deep Learning projects for final year into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Deep Learning Projects for Final Year even arrange a more significant compensation.
Python Training in Chennai Project Centers in Chennai
Can you please share the WAR file? It will be really help full to deploy and test?
ReplyDeleteThanks
Shared the project, please download it
Deleteafter getting access token i am unable to get the user info
ReplyDeleteshare correct exception or error
DeleteHi 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
ReplyDeleteI am getting the same error. Please explain
ReplyDeleteentering doGet
java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
leaving doGet
Hi,
ReplyDeleteplease share your file, it will be helpful
Shared the project, please download it
Deleteplease share the project Srinivas.
ReplyDeletehttp://downloads.sodhanalibrary.com/download?id=11
DeleteU need to subscribe to download it
Hello Dasari, i registed my e-mail by http://downloads.sodhanalibrary.com/download?id=11, but i can't download it.
ReplyDeletetry now
DeleteHi... Which Libraries are required ....????
ReplyDeleteno special libraries needed, just google-gson (https://github.com/google/gson) is enough
Deletehi! if i have done my site whit tomcat, can i do this tutorial?
ReplyDeletebecause 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?
Go to Google developer console, add your localhost url under "Authorized redirect URIs"
Deletehi 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(
ReplyDeleteconn.getOutputStream());
This is due to HTTPS (SSL Certificate), this might help you http://blog.sodhanalibrary.com/2015/12/how-to-solve-javaxnetsslsslhandshakeexc.html#.WD_LtqJ95hE
DeleteSir when my web page redirect then some error:
ReplyDeleteerror 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
Check your web.xml configuration
Deletejava.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
Deletehow to solve this error
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
DeleteHello Srinivas Dasari,
ReplyDeleteThere 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.
From last 2 days, the server didnt update properly. sorry for the inconvenience, Now its working fine. Make sure that your feedburner subscription verified
DeleteHello Srinivas Dasari,
ReplyDeletejava.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
401 error means unauthorised access. Check client_id and client_secret in urlParameters
DeleteHello Srinivas Dasari,
ReplyDeletenothing 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??
You should add that URL in Google developer console app settings
Deletesir getting error
ReplyDeleteServer returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
Please help... where is there error can you tell me
I am getting the same error. Please explain
ReplyDeleteentering doGet
java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
leaving doGet please help me
I have an error "HTTP Status 500 - java.lang.NullPointerException" ! help me
ReplyDeletesir can you give me the netbeans realated project
ReplyDeletehello,
ReplyDeletewhen 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???
hiii, i am trying with this code but it is showing a error of javax.servlet.ServletException: Servlet execution threw an exception
ReplyDeleteorg.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)
I have created new project on Google Developer Console with below details:
ReplyDeletepublic 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?
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,
ReplyDeleteplease share code
ReplyDeleteThanks for sharing us. Buy Pinterest Followers
ReplyDeleteI found your this post while searching for some related information on blog search Its a good post. สมัครสมาชิก 123betting
ReplyDeleteExtremely useful information specifically the ultimate section I handle such info much. virx สเปรย์พ่นจมูก
ReplyDeleteشركه شراء اثاث مستعمل
ReplyDeleteشراء أثاث مستعمل بالرياض