- 浏览: 2490030 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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(2)Scala and Callback URLs
OauthService.scala Codes to Generate AuthURL/Fetch RefreshToken/Fetch Profile
package services
import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.{GoogleTokenResponse, GoogleAuthorizationCodeRequestUrl}
import com.jobs2careers.util.IncludeLogger
import models.{ AccountProfileResponse}
import play.api.libs.json.Json
import play.api.libs.ws.{WSResponse, WS}
import utils.IncludeOauthConfig
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.concurrent.Future
import play.api.Play.current
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.GmailScopes
object OauthService extends IncludeOauthConfig with IncludeLogger{
implicit val accountProfileResponseWrites = Json.writes[AccountProfileResponse]
implicit val accountProfileResponseReads = Json.reads[AccountProfileResponse]
val callbackURL = OAUTH_CALLBACK_URI
val USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile"
val EMAIL_INFO_URL = "https://www.googleapis.com/auth/userinfo.email"
val USER_PROFILE_URL = "https://www.googleapis.com/oauth2/v1/userinfo"
val JSON_FACTORY:JsonFactory = new JacksonFactory()
val HTTP_TRANSPORT:HttpTransport = new NetHttpTransport()
def generateAuthURL(accountCode:String):String = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
val url:GoogleAuthorizationCodeRequestUrl = flow.newAuthorizationUrl()
val url_str = url.setRedirectUri(callbackURL).setState(accountCode).build()
//url_str = url_str + "&login_hint=ipply@jobs2careers.com";
return url_str
}
def fetchRefreshToken(accessToken:String):String = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
val response:GoogleTokenResponse = flow.newTokenRequest(accessToken)
.setRedirectUri(callbackURL).execute()
val refreshToken = response.getRefreshToken()
logger.debug("Refresh token system get = " + refreshToken)
return refreshToken
}
def fetchEmail(refreshToken:String): Option[String] = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
logger.debug("Refresh Token = " + refreshToken)
val tokenResponse:TokenResponse = new TokenResponse()
tokenResponse.setRefreshToken(refreshToken)
val credential:Credential = flow.createAndStoreCredential(tokenResponse, null)
val requestFactory:HttpRequestFactory = HTTP_TRANSPORT.createRequestFactory(credential)
// Make an authenticated request
val genericUrl:GenericUrl = new GenericUrl(USER_INFO_URL)
val request:HttpRequest = requestFactory.buildGetRequest(genericUrl)
request.getHeaders().setContentType("application/json")
request.execute()
val accessToken = credential.getAccessToken()
logger.debug("System get the new Access Token = " + accessToken)
// {
// "id": "114122167329329897934",
// "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"
// }
val url = USER_PROFILE_URL + "?alt=json&access_token=" + accessToken
logger.debug("URL = " + url)
val future:Future[WSResponse] = WS.url(url).get()
val result = Await.result(future, 20 seconds)
logger.debug("Fetching the profile response = " + result.json + " accessToken = " + accessToken)
val email = result.json.asOpt[AccountProfileResponse].map { profile =>
logger.info("Fetching the profile information = " + profile)
profile.email
}
return email
}
}
The Callback URL who handle the Callback
def addSource = Action { request =>
logger.debug("The request body = " + request.body)
val accessToken = request.getQueryString("code").getOrElse("")
val accountCode = request.getQueryString("state").getOrElse("")
logger.debug("First access token system get = " + accessToken)
if(accessToken.isEmpty || accountCode.isEmpty){
val warn_msg = "Callback add source fail, request params accountCode = " + accountCode
logger.warn(warn_msg)
BadRequest(Json.obj("status" -> "Fail", "message" -> warn_msg))
}else{
val refreshToken = OauthService.fetchRefreshToken(accessToken)
val email = OauthService.fetchEmail(refreshToken).getOrElse("")
if(email.isEmpty){
val warn_msg = "Callback add source fail, fail to fetch email with refreshToken."
logger.warn(warn_msg)
BadRequest(Json.obj("status" -> "Fail", "message" -> warn_msg))
}else{
//call actor to ContextIO to add source
sillycatIOthrottler ! AccountSourceMessage(
accountCode, //accountCode
email, //email system fetch from profile
email, //username, same as email for google
refreshToken //refreshToken
)
Ok(Json.obj("status" -> "OK"))
}
}
}
The dependencies in build.sbt
"com.google.api-client" % "google-api-client" % "1.20.0",
"com.google.oauth-client" % "google-oauth-client" % "1.20.0",
"com.google.apis" % "google-api-services-gmail" % "v1-rev36-1.20.0",
References:
http://sillycat.iteye.com/blog/2274258
OauthService.scala Codes to Generate AuthURL/Fetch RefreshToken/Fetch Profile
package services
import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.{GoogleTokenResponse, GoogleAuthorizationCodeRequestUrl}
import com.jobs2careers.util.IncludeLogger
import models.{ AccountProfileResponse}
import play.api.libs.json.Json
import play.api.libs.ws.{WSResponse, WS}
import utils.IncludeOauthConfig
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.concurrent.Future
import play.api.Play.current
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.GmailScopes
object OauthService extends IncludeOauthConfig with IncludeLogger{
implicit val accountProfileResponseWrites = Json.writes[AccountProfileResponse]
implicit val accountProfileResponseReads = Json.reads[AccountProfileResponse]
val callbackURL = OAUTH_CALLBACK_URI
val USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile"
val EMAIL_INFO_URL = "https://www.googleapis.com/auth/userinfo.email"
val USER_PROFILE_URL = "https://www.googleapis.com/oauth2/v1/userinfo"
val JSON_FACTORY:JsonFactory = new JacksonFactory()
val HTTP_TRANSPORT:HttpTransport = new NetHttpTransport()
def generateAuthURL(accountCode:String):String = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
val url:GoogleAuthorizationCodeRequestUrl = flow.newAuthorizationUrl()
val url_str = url.setRedirectUri(callbackURL).setState(accountCode).build()
//url_str = url_str + "&login_hint=ipply@jobs2careers.com";
return url_str
}
def fetchRefreshToken(accessToken:String):String = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
val response:GoogleTokenResponse = flow.newTokenRequest(accessToken)
.setRedirectUri(callbackURL).execute()
val refreshToken = response.getRefreshToken()
logger.debug("Refresh token system get = " + refreshToken)
return refreshToken
}
def fetchEmail(refreshToken:String): Option[String] = {
val flow:GoogleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET,
Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
.setAccessType("offline")
.setApprovalPrompt("force")
.build()
logger.debug("Refresh Token = " + refreshToken)
val tokenResponse:TokenResponse = new TokenResponse()
tokenResponse.setRefreshToken(refreshToken)
val credential:Credential = flow.createAndStoreCredential(tokenResponse, null)
val requestFactory:HttpRequestFactory = HTTP_TRANSPORT.createRequestFactory(credential)
// Make an authenticated request
val genericUrl:GenericUrl = new GenericUrl(USER_INFO_URL)
val request:HttpRequest = requestFactory.buildGetRequest(genericUrl)
request.getHeaders().setContentType("application/json")
request.execute()
val accessToken = credential.getAccessToken()
logger.debug("System get the new Access Token = " + accessToken)
// {
// "id": "114122167329329897934",
// "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"
// }
val url = USER_PROFILE_URL + "?alt=json&access_token=" + accessToken
logger.debug("URL = " + url)
val future:Future[WSResponse] = WS.url(url).get()
val result = Await.result(future, 20 seconds)
logger.debug("Fetching the profile response = " + result.json + " accessToken = " + accessToken)
val email = result.json.asOpt[AccountProfileResponse].map { profile =>
logger.info("Fetching the profile information = " + profile)
profile.email
}
return email
}
}
The Callback URL who handle the Callback
def addSource = Action { request =>
logger.debug("The request body = " + request.body)
val accessToken = request.getQueryString("code").getOrElse("")
val accountCode = request.getQueryString("state").getOrElse("")
logger.debug("First access token system get = " + accessToken)
if(accessToken.isEmpty || accountCode.isEmpty){
val warn_msg = "Callback add source fail, request params accountCode = " + accountCode
logger.warn(warn_msg)
BadRequest(Json.obj("status" -> "Fail", "message" -> warn_msg))
}else{
val refreshToken = OauthService.fetchRefreshToken(accessToken)
val email = OauthService.fetchEmail(refreshToken).getOrElse("")
if(email.isEmpty){
val warn_msg = "Callback add source fail, fail to fetch email with refreshToken."
logger.warn(warn_msg)
BadRequest(Json.obj("status" -> "Fail", "message" -> warn_msg))
}else{
//call actor to ContextIO to add source
sillycatIOthrottler ! AccountSourceMessage(
accountCode, //accountCode
email, //email system fetch from profile
email, //username, same as email for google
refreshToken //refreshToken
)
Ok(Json.obj("status" -> "OK"))
}
}
}
The dependencies in build.sbt
"com.google.api-client" % "google-api-client" % "1.20.0",
"com.google.oauth-client" % "google-oauth-client" % "1.20.0",
"com.google.apis" % "google-api-services-gmail" % "v1-rev36-1.20.0",
References:
http://sillycat.iteye.com/blog/2274258
发表评论
-
Stop Update Here
2020-04-28 09:00 267I 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 316Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 325Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 297Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 383Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 379Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 331Docker 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 339Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 420NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 365Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 294Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 214GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 395GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 279GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 267Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 268Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 255Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 240Serverless with NodeJS and Tenc ...
相关推荐
Scala OAuth2 这是一个scala OAuth2客户端库。
scala-oauth2-provider:用Scala编写的OAuth 2.0服务器端实现
sttp-oauth2-Scala的OAuth2客户端库该库旨在使用客户端与基于OAuth2提供程序轻松集成。 它使用进行JSON序列化/反序列化。 当前,它支持用于获取授权的方法(授权类型):用法sttp-oauth2 每个授予都在具有方法的显式...
yii2-oauth2-server, 用于实现OAuth2服务器的包装器( https yii2-oauth2-server用于实现OAuth2服务器的包装器( https://github.com/bshaffer/oauth2-server-php 插件)安装安装这里扩展的首选方法是通过 Composer 。...
springboot和apache的开源项目org.apache.oltu.oauth2组合搭建的oauth2环境,一般的oauth配置下就可以用了,但是我这个项目,是用原理上讲如何搭建oauth2,哪个controller转发到哪个controller,为什么这样,都有...
赠送jar包:spring-security-oauth2-2.3.5.RELEASE.jar; 赠送原API文档:spring-security-oauth2-2.3.5.RELEASE-javadoc.jar; 赠送源代码:spring-security-oauth2-2.3.5.RELEASE-sources.jar; 赠送Maven依赖信息...
#OAuth2-Defender ##主要技术 Maven Spring Boot Spring Security Spring Security OAuth2.0 MySQL ##修改数据库配置 修改defender-oauth2-authorization\src\main\resources\...
oauth2oauth2oauth2
Laravel开发-oauth2-social-login 一个简单的OAuth2社会登录助手
还在烦恼OAuth2技术只依赖boot吗?我提供了纯java技术实现OAuth2的全部实现,含客户端和服务端的完整解决方案。
模拟OAuth2 单点登录的java代码实现。模拟OAuth2 单点登录的java代码实现。模拟OAuth2 单点登录的java代码实现。模拟OAuth2 单点登录的java代码实现。
使用spring oauth2框架做授权鉴定。想获取当前用户信息怎么办? 我们知道spring oauth2是基于spring security的实现的。 spring security可以通过SecurityContextHolder.getContext().getAuthentication()....
基于微服务架构理念设计的开放平台接口,采用oauth2.0协议,使用springcould技术搭建的Maven服务,包含两个服务...oauth2调用接口简易文档,是接口使用简单文档,oauth2.sql是遵循oauth2协议规范的数据库表设计sql语句
包含 1.Getting Started with OAuth 2.0.pdf 2.Mastering OAuth 2.0.pdf 3.Oauth2 in Action.pdf 4.OAuth2.0 Cookbook.pdf
OAuth 2 0 is the next evolution of the OAuth protocol which was originally created in late 2006 OAuth 2 0 focuses on client developer simplicity while providing specific authorization flows for web a
使用作曲家: $ composer require kronthto/laravel-oauth2-login 注册服务提供商(启用自动发现): Kronthto\LaravelOAuth2Login\ServiceProvider 发布配置文件: $ artisan vendor:publish --provider=...
springboot整合Oauth2,GateWay实现网关登录授权验证
spring security oauth2的源码,方便研究,备份一下。
spring-oauth2-login
Laravel开发-laravel-oauth2-login 提供中间件以保护需要OAuth2登录的资源