您可以使用 jwt-decode
库来解码您的凭据 OAuth 登录,以下是逐步使用它的步骤
- 安装
jwt-decode
您可以使用 npm install jwt-decode
或 yarn add jwt-decode
或 pnpm install jwt-decode
- 将
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);
}
}
}
...
我使用来自@react-oauth/google
的GoogleLoginOAuth,在我的情况下,这段代码可以正常工作!
还有一件事,**只是插曲**如果您使用TypeScript,则希望解构对象以获取例如name
或family_name
。
const { given_name, family_name } = USER_CREDENTIAL;
然后你会得到这样的错误波浪线
Property 'family_name' does not exist on type 'unknown'
你可以像这样制作类型,如果需要,可以复制它
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
}
然后你可以像这样编写你的代码
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)
}
}
}
...
希望能够有所帮助!