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

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

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

  1. {
  2. "clientId": "xxx...apps.googleusercontent.com",
  3. "credential": "yyy...123...zzz",
  4. "select_by": "user"
  5. }

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

nzkunb0c

nzkunb0c1#

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

  1. const { OAuth2Client } = require('google-auth-library')
  2. /**
  3. * @description Function to decode Google OAuth token
  4. * @param token: string
  5. * @returns ticket objet
  6. */
  7. export const getDecodedOAuthJwtGoogle = async token => {
  8. const CLIENT_ID_GOOGLE = 'yourGoogleClientId'
  9. try {
  10. const client = new OAuth2Client(CLIENT_ID_GOOGLE)
  11. const ticket = await client.verifyIdToken({
  12. idToken: token,
  13. audience: CLIENT_ID_GOOGLE,
  14. })
  15. return ticket
  16. } catch (error) {
  17. return { status: 500, data: error }
  18. }
  19. }

用法:

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

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

  1. {
  2. // These six fields are included in all Google ID Tokens.
  3. "iss": "https://accounts.google.com",
  4. "sub": "110169484474386276334",
  5. "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  6. "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
  7. "iat": "1433978353",
  8. "exp": "1433981953",
  9. // These seven fields are only included when the user has granted the "profile" and
  10. // "email" OAuth scopes to the application.
  11. "email": "testuser@gmail.com",
  12. "email_verified": "true",
  13. "name" : "Test User",
  14. "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
  15. "given_name": "Test",
  16. "family_name": "User",
  17. "locale": "en"
  18. }
展开查看全部

相关问题