javascript - 如何解码 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。
用户通过身份验证后,如何向应用程序提供真实的用户数据?
解决方案
经过反复尝试,很明显标准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"
}
推荐阅读
- python - 如何将用于获取语音频道中成员列表的 discord.py discord 机器人代码转换为新的 discord.py 版本?
- java - 读取缓冲图像显示透明度但输出错误的 alpha 值
- python-3.x - 无法使用 slack api files.upload 上传文件
- json - 在 awk 中的每条记录之前和之后打印
- php - 即使在会话之前我没有其他输出,为什么我仍然会收到会话缓存限制器错误
- c# - 将 SQL Server Serilog 接收器包装在 Async 中是否有意义?
- cmd - 删除最后一个 WMIC 属性值的空格并添加另一个字符串
- jquery - 隐藏特定 Jquery UI 微调器的微调器按钮
- javascript - 如何修复我的动态下拉菜单。它不会发火
- css - 从 Wikipedia Print Preview 中删除超链接下划线