[英]How can I decode a google OAuth 2.0 JWT / credential token?
I'm building a browser app that requires to authenticate with Google using the OAuth 2.0 / JWT workflow outlined in the link .我正在构建一个浏览器应用程序,需要使用链接中概述的 OAuth 2.0 / JWT 工作流程向 Google 进行身份验证。
In the scenario of success user authentication with Google OAuth 2.0, Google API sends to an app OAuth the response like this:在使用 Google OAuth 2.0 成功进行用户身份验证的情况下,Google API 向应用程序 OAuth 发送如下响应:
{
"clientId": "xxx...apps.googleusercontent.com",
"credential": "yyy...123...zzz",
"select_by": "user"
}
I have a client_id and using the NodeJS + JS.我有一个 client_id 并使用 NodeJS + JS。
How can I provide the app with the real user data once the user is authenticated?用户通过身份验证后,如何向应用程序提供真实用户数据?
After some forth and back attempts it got clear that standard import jwt from 'jsonwebtoken'
does not work and Google uses its own encoding npm library - google-auth-library
, see more here .经过一番反复尝试后,很明显
import jwt from 'jsonwebtoken'
标准import jwt from 'jsonwebtoken'
不起作用,Google 使用自己的编码 npm 库 - google-auth-library
,请在此处查看更多信息。 The basic solution is the following:基本解决方案如下:
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 }
}
}
Usage:用法:
const realUserData = getDecodedOAuthJwtGoogle(credential) // credentials === JWT token
If your token (credential) is valid then realUserData
will hopefully have a value like this:如果您的令牌(凭证)有效,那么
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"
}
You can use jwt-decode
library to decode your credential OAuth Login, here is the step by step how to use it您可以使用
jwt-decode
库来解码您的凭据 OAuth 登录,这里是逐步使用方法
jwt-decode
jwt-decode
You can use npm install jwt-decode
or yarn add jwt-decode
or pnpm install jwt-decode
您可以使用
npm install jwt-decode
或yarn add jwt-decode
或pnpm install jwt-decode
jwt-decode
to your App jwt-decode
导入您的应用程序
import { GoogleLogin } from '@react-oauth/google';
import jwtDecode from 'jwt-decode'
...
<GoogleLogin
onSuccess = {credentialResponse => {
if (credentialResponse.credential != null) {
const USER_CREDENTIAL = jwtDecode(credentialResponse.credential);
console.log(USER_CREDENTIAL);
}
}
}
...
I use GoogleLoginOAuth from @react-oauth/google
, at my case this code it's work!我使用来自
@react-oauth/google
GoogleLoginOAuth,在我的例子中,这段代码有效!
One more thing, ** just intermezzo ** if you use TypeScript, then you want destructure object to get name
or family_name
for instance还有一件事,** 只是插曲 ** 如果你使用 TypeScript,那么你想要解构 object 以获取
name
或family_name
例如
const { given_name, family_name } = USER_CREDENTIAL;
and then you get this error squiggles like this然后你会得到这样的错误波浪线
Property 'family_name' does not exist on type 'unknown'
You can make type like this, copy it if you need it anyway你可以像这样制作类型,如果你需要它就复制它
dataCredential.ts
export type dataCredential = {
aud: string,
azp: string,
email: string,
email_verified: boolean,
exp: number,
family_name: string,
given_name: string,
iss: string,
jti: string,
name: string,
nbf: number,
picture: string,
sub: string
}
and than you can make your code like this然后你可以像这样制作你的代码
import { GoogleLogin } from '@react-oauth/google';
import jwtDecode from 'jwt-decode'
import {dataCredential} from "../types/dataCredential";
...
<GoogleLogin
onSuccess = {credentialResponse => {
if (credentialResponse.credential != null) {
const USER_CREDENTIAL: dataCredential = jwtDecode(credentialResponse.credential);
console.log(USER_CREDENTIAL);
const { given_name, family_name } = USER_CREDENTIAL;
console.log(given_name, family_name)
}
}
}
...
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.