首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从google登录获取ID令牌

从google登录获取ID令牌
EN

Stack Overflow用户
提问于 2022-07-20 09:42:40
回答 1查看 149关注 0票数 0

我正在尝试使用在oauth模块中内置的http4k在我的后端应用程序中实现Google登录。

以下是我到目前为止所拥有的:

代码语言:javascript
复制
val googleClientId = "<GoogleClientID>"
val googleClientSecret = "<GoogleClientSecret>"

// this is a test implementation of the OAuthPersistence interface, which should be
// implemented by application developers
val oAuthPersistence = InsecureCookieBasedOAuthPersistence("Google")

// pre-defined configuration exist for common OAuth providers
val oauthProvider = OAuthProvider.google(
  JavaHttpClient(),
  Credentials(googleClientId, googleClientSecret),
  Uri.of("http://localhost:9000/oauth/callback"),
  oAuthPersistence
)
val app: HttpHandler = routes(
  "/oauth" bind routes(
    "/" bind GET to oauthProvider.authFilter.then {
      val user = contextFn(it)
      Response(OK).body("authenticated!")
    },
    "/callback" bind GET to oauthProvider.callback
)
app.asServer(SunHttp(9000)).start()

这让我可以去http://localhost:9000/oauth,我可以登录到我的google帐户。凉爽的!

然而,在重定向之后,我将转到以下函数contextFn,它类似于这个atm:

代码语言:javascript
复制
val transport = NetHttpTransport()
val jsonFactory = GsonFactory.getDefaultInstance()

val verifier = GoogleIdTokenVerifier.Builder(transport, jsonFactory)
  .setAudience(listOf(googleClientId))
  .build()

fun contextFn(request: Request): Principal {
  // TODO: get the id token somehow, but the request header only contains the following in cookie:
  // - GoogleCsrf
  // - GoogleAccessToken
  // - GoogleOriginalUri
  val idTokenString = ""

  val idToken: GoogleIdToken = verifier.verify(idTokenString)
  val payload: GoogleIdToken.Payload = idToken.payload

  // Print user identifier
  val userId: String = payload.subject
  println("User ID: $userId")

  // Get profile information from payload
  val email: String = payload.email
  val emailVerified: Boolean = payload.emailVerified
  val name = payload["name"]

  return GoogleUser(email)
}

我怎样才能拿到身份证呢?目前,我正在从谷歌获得访问令牌。

EN

回答 1

Stack Overflow用户

发布于 2022-07-20 14:33:28

您能尝试添加这个scope(openid)?吗?我不确定listOf或addScope对http4k的支持,但它忽略了openid范围。

代码语言:javascript
复制
val oauthProvider = OAuthProvider.google(
  JavaHttpClient(),
  Credentials(googleClientId, googleClientSecret),
  Uri.of("http://localhost:9000/oauth/callback"),
  listOf("openidScope"),
  oAuthPersistence
)
oauthProvider.addScope('openid');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73049310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档