- 浏览: 2487936 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
OAuth Login Solution(1)Java Codes
1 Implementation in Java
Some Dependencies in build.gradle
compile 'com.google.api-client:google-api-client:1.20.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
compile 'com.google.apis:google-api-services-gmail:v1-rev29-1.20.0'
Class Generate the Auth URL in OauthGmailApp.java
package com.sillycat.gmailapi;
import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;
public class OauthGmailApp {
private static final String CLIENT_ID = "43144392xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxx";
private static final String CALLBACK_URI = "http://requestb.in/xxxxxxx";
private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";
private static final String EMAIL_INFO_URL = "https://www.googleapis.com/auth/userinfo.email";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
//Arrays.asList(GmailScopes.GMAIL_READONLY)
//GmailScopes.all()
public static void main(String[] args) {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
String url_str = url.setRedirectUri(CALLBACK_URI).setState("accountId123").build();
url_str = url_str + "&login_hint=luohuazju@gmail.com";
System.out.println("URL = " + url_str );
}
}
This Class will print out the Auth URL, with this URL, we can open a chrome window, put our gmail name and password to authorize the permission.
Google will call the callback URL with information like this:
state=accountId123&code=4/TL65z3EXA0Ls6b9pWIaAxxxxxxxxxxxx
The code is an accessToken, we can use it once. The state is just an identifier for us. We pass in the ‘accountId123’, then we receive ‘accountId123’.
The class Fetch the RefreshToken in OauthGmailTokenFetchApp.java
package com.sillycat.gmailapi;
import java.io.IOException;
import java.util.Arrays;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;
public class OauthGmailTokenFetchApp {
private static final String CLIENT_ID = "431443920320-540ruq1xxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxx";
private static final String CALLBACK_URI = "http://requestb.in/xxxxxxxxx";
private static final String authCode = "4/iXvUVF79HNMhntMqxxxxxxxxxxxxxxxx";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static void main(String[] args) throws IOException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.GMAIL_READONLY)).setAccessType("offline").setApprovalPrompt("force").build();
GoogleTokenResponse response = flow.newTokenRequest(authCode)
.setRedirectUri(CALLBACK_URI).execute();
System.out.println("Refresh Token = " + response.getRefreshToken());
}
}
Use the AccessToken we get from the step one, we can fetch the refresh token, we need keep this refresh token secret, because this refresh token can always get the access token.
The Class Generate a new AccessToken and Fetch User Profile in OauthGmailFetchInfoApp.java
package com.sillycat.gmailapi;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
public class OauthGmailFetchInfoApp {
private static final String CLIENT_ID = “431443920320-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxxx";
private static final String REFRESH_TOKEN = "1/poLb6SOjE7TRCOdZ9WCX54Qzxxxxxxxxxxxxxxx";
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static void main(String[] args) throws IOException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.GMAIL_READONLY))
.setAccessType("offline").setApprovalPrompt("force").build();
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setRefreshToken(REFRESH_TOKEN);
Credential credential = flow.createAndStoreCredential(tokenResponse,
null);
// Gmail maiService = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
//
// String user = "me";
// ListLabelsResponse listResponse = maiService.users().labels().list(user)
// .execute();
// List<Label> labels = listResponse.getLabels();
// if (labels.size() == 0) {
// System.out.println("No labels found.");
// } else {
// System.out.println("Labels:");
// for (Label label : labels) {
// System.out.printf("- %s\n", label.getName());
// }
// }
final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
// Make an authenticated request
final GenericUrl url = new GenericUrl(USER_INFO_URL);
final HttpRequest request = requestFactory.buildGetRequest(url);
request.getHeaders().setContentType("application/json");
//request.execute().parseAsString();
request.execute();
//System.out.println(new String(jsonIdentity.getBytes()));
System.out.println("accesstoken = " + credential.getAccessToken());
//https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A
}
}
Once we get the accessToken, we can visit the user profile from the link at the very bottom like this.
https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A
The return value will be as JSON format as follow:
{
"id": “xxxxxxxxxx",
"email": “luohuazju@gmail.com",
"verified_email": true,
"name": “Sillycat Mobile",
"given_name": “Sillycat",
"family_name": "Mobile",
"picture": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg",
"locale": "en",
"hd": “gmail.com"
}
References:
https://console.developers.google.com
1 Implementation in Java
Some Dependencies in build.gradle
compile 'com.google.api-client:google-api-client:1.20.0'
compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
compile 'com.google.apis:google-api-services-gmail:v1-rev29-1.20.0'
Class Generate the Auth URL in OauthGmailApp.java
package com.sillycat.gmailapi;
import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;
public class OauthGmailApp {
private static final String CLIENT_ID = "43144392xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxx";
private static final String CALLBACK_URI = "http://requestb.in/xxxxxxx";
private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";
private static final String EMAIL_INFO_URL = "https://www.googleapis.com/auth/userinfo.email";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
//Arrays.asList(GmailScopes.GMAIL_READONLY)
//GmailScopes.all()
public static void main(String[] args) {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build();
GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
String url_str = url.setRedirectUri(CALLBACK_URI).setState("accountId123").build();
url_str = url_str + "&login_hint=luohuazju@gmail.com";
System.out.println("URL = " + url_str );
}
}
This Class will print out the Auth URL, with this URL, we can open a chrome window, put our gmail name and password to authorize the permission.
Google will call the callback URL with information like this:
state=accountId123&code=4/TL65z3EXA0Ls6b9pWIaAxxxxxxxxxxxx
The code is an accessToken, we can use it once. The state is just an identifier for us. We pass in the ‘accountId123’, then we receive ‘accountId123’.
The class Fetch the RefreshToken in OauthGmailTokenFetchApp.java
package com.sillycat.gmailapi;
import java.io.IOException;
import java.util.Arrays;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;
public class OauthGmailTokenFetchApp {
private static final String CLIENT_ID = "431443920320-540ruq1xxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxx";
private static final String CALLBACK_URI = "http://requestb.in/xxxxxxxxx";
private static final String authCode = "4/iXvUVF79HNMhntMqxxxxxxxxxxxxxxxx";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static void main(String[] args) throws IOException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.GMAIL_READONLY)).setAccessType("offline").setApprovalPrompt("force").build();
GoogleTokenResponse response = flow.newTokenRequest(authCode)
.setRedirectUri(CALLBACK_URI).execute();
System.out.println("Refresh Token = " + response.getRefreshToken());
}
}
Use the AccessToken we get from the step one, we can fetch the refresh token, we need keep this refresh token secret, because this refresh token can always get the access token.
The Class Generate a new AccessToken and Fetch User Profile in OauthGmailFetchInfoApp.java
package com.sillycat.gmailapi;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
public class OauthGmailFetchInfoApp {
private static final String CLIENT_ID = “431443920320-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxxx";
private static final String REFRESH_TOKEN = "1/poLb6SOjE7TRCOdZ9WCX54Qzxxxxxxxxxxxxxxx";
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static void main(String[] args) throws IOException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(GmailScopes.GMAIL_READONLY))
.setAccessType("offline").setApprovalPrompt("force").build();
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setRefreshToken(REFRESH_TOKEN);
Credential credential = flow.createAndStoreCredential(tokenResponse,
null);
// Gmail maiService = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
//
// String user = "me";
// ListLabelsResponse listResponse = maiService.users().labels().list(user)
// .execute();
// List<Label> labels = listResponse.getLabels();
// if (labels.size() == 0) {
// System.out.println("No labels found.");
// } else {
// System.out.println("Labels:");
// for (Label label : labels) {
// System.out.printf("- %s\n", label.getName());
// }
// }
final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
// Make an authenticated request
final GenericUrl url = new GenericUrl(USER_INFO_URL);
final HttpRequest request = requestFactory.buildGetRequest(url);
request.getHeaders().setContentType("application/json");
//request.execute().parseAsString();
request.execute();
//System.out.println(new String(jsonIdentity.getBytes()));
System.out.println("accesstoken = " + credential.getAccessToken());
//https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A
}
}
Once we get the accessToken, we can visit the user profile from the link at the very bottom like this.
https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A
The return value will be as JSON format as follow:
{
"id": “xxxxxxxxxx",
"email": “luohuazju@gmail.com",
"verified_email": true,
"name": “Sillycat Mobile",
"given_name": “Sillycat",
"family_name": "Mobile",
"picture": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg",
"locale": "en",
"hd": “gmail.com"
}
References:
https://console.developers.google.com
发表评论
-
Stop Update Here
2020-04-28 09:00 264I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 433NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 313Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 323Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 294Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 381Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 378Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 329Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 403VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 337Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 419NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 363Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 293Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 211GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 393GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 278GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 266Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 266Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 253Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 240Serverless with NodeJS and Tenc ...
相关推荐
Java的oauth2.0 服务端与客户端的实现.zip 封装了oauth2.0的基本架构和实现,对照我的博客http://blog.csdn.net/jing12062011/article/details/78147306使用该源码。 下载项目压缩包,解压,里面两个maven项目:...
还在烦恼OAuth2技术只依赖boot吗?我提供了纯java技术实现OAuth2的全部实现,含客户端和服务端的完整解决方案。
微博Oauth2.0 协议,用java 实现单点登录获取用户信息。
oauth本身不是技术,而是一项资源授权协议,重点是协议!Apache基金会提供了针对Java的oauth封装。我们做Java web项目想要实现oauth协议进行资源授权访问,直接使用该封装就可以。
资源为在eclipse开发环境中使用Java搭建OAuth Server和OAuth Client 参考代码为http://code.google.com/p/oauth/ OAuth Server为遵守OAuth 1.0协议的OAuth认证服务器 OAuth Client分为Desktop版本和Webapp版本
基于MAVEN+OLTU开源代码实现javaOauth2.0前后端,数据加密使用MD5。
基于java的开发源码-API访问授权的开放标准 OAuth.zip 基于java的开发源码-API访问授权的开放标准 OAuth.zip 基于java的开发源码-API访问授权的开放标准 OAuth.zip 基于java的开发源码-API访问授权的开放标准 OAuth....
Google OAuth Client Library for Java
Java的oauth2.0 服务端与客户端的实现源码下载,里面两个maven项目:oauthserver和oauthclient01。
oauth2密码模式的java版本,服务端和客户端,希望能帮助到大家
Oauth2 Java demo
一套完整的 google drive 认证系统,可以根据以下命令编译运行: 将申请的Client ID和Client secrets加入到client_secrets.json cd . (当前源码根路径) mkdir bin ..." com.google.oauth2.Oauth2
Java的oauth2.0 服务端与客户端的实现.zip 封装了oauth2.0的基本架构和实现
小米oauth2.0java实现以及第三方云接入,实现了多种参数的接口9state.response_type,client_id,client_secret等)
真情大奉献,给你详细的技术细节,里面有作者的联系方式,有疑问的话,欢迎随时交流,一起提高,一起进步哦亲!
sina weibo oauth2.0 java jsp 例子内赋使用说明,直接导入
OAuth2.0 JAVA服务端和客户端功能实现(带jar包)
oauth2-java-demo-masterOAuth2.0是OAuth协议的延续版本,但不向后兼容OAuth 1.0即完全废止了OAuth1.0。 OAuth 2.0关注客户端开发者的简易性。
springboot 集成oauth2.0服务器,基于oauth2.0授权码形式集成
Java的oauth2.0 服务端与客户端的实现。 压缩包解压里面两个maven项目:oauthserver和oauthclient01,分别对应oauth服务端和客户端。