首页 > 解决方案 > 如何解码 google OAuth 2.0 JWT / 凭证令牌?

问题描述

我正在构建一个浏览器应用程序,该应用程序需要使用链接中概述的 OAuth 2.0/JWT 工作流向 Google 进行身份验证。

在使用 Google OAuth 2.0 成功进行用户身份验证的场景中,Google API 向应用程序 OAuth 发送如下响应:

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

我有一个 client_id 并使用 NodeJS + JS。

用户通过身份验证后,如何向应用程序提供真实的用户数据?

标签: javascriptnode.jsoauth-2.0oauthgoogle-oauth

解决方案


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

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

/**
 * @description Function to decode Google OAuth token
 * @param token: string
 * @returns ticket object
 */
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 }
  }
}

用法:

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

如果您的令牌(凭证)是有效的,那么realUserData希望有这样的值:

{
  // 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"
}

推荐阅读