如何解码google oauth 2.0 jwt/credential令牌?

92dk7w1h  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(715)

我正在构建一个浏览器应用程序,它需要使用链接中概述的oauth 2.0/jwt工作流向google进行身份验证。
google oauth 2.0 oauth响应如下:

{
  "clientId": "xxx...apps.googleusercontent.com",
  "credential": "yyy...123...zzz",
  "select_by": "user"
}

我有一个客户端id。我正在使用nodejs+js。
一旦用户通过身份验证,我如何向应用程序提供真实的用户数据?

nzkunb0c

nzkunb0c1#

经过反复的尝试之后,很明显,这个标准 import jwt from 'jsonwebtoken' 不起作用,谷歌使用自己的编码npm库- google-auth-library ,请在此查看更多。基本解决方案如下:

const { OAuth2Client } = require('google-auth-library')

/**
 * @description Function to decode Google OAuth token
 * @param token: string
 * @returns ticket objet
 */
export const getDecodedOAuthJwtGoogle = async token => {

  const CLIENT_ID_GOOGLE = 'yourGoogleClientId'

  try {
    const client = new OAuth2Client(CLIENT_ID_GOOGLE)

    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID_GOOGLE,
    })

    return ticket
  } catch (error) {
    return { status: 500, data: error }
  }
}

用法:

getDecodedOAuthJwtGoogle(credential) // credentials === JWT token

如果您的令牌(凭证)有效,则希望返回如下内容:

{
  // These six fields are included in all Google ID Tokens.
  "iss": "https://accounts.google.com",
  "sub": "110169484474386276334",
  "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  "iat": "1433978353",
  "exp": "1433981953",

  // These seven fields are only included when the user has granted the "profile" and
  // "email" OAuth scopes to the application.
  "email": "testuser@gmail.com",
  "email_verified": "true",
  "name" : "Test User",
  "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
  "given_name": "Test",
  "family_name": "User",
  "locale": "en"
}

相关问题