我已经为我的登录页面实现了使用 google 功能登录,并且使用了
@react-oauth/google
包。在我的应用程序中,要调度登录操作,我需要 4 件事 - 姓名、电子邮件、令牌和 googleId。 react-google-login
包裹,在那里我得到了所有这些物品。但从当前的包文档中我发现......
import { GoogleLogin } from '@react-oauth/google';
<GoogleLogin
onSuccess={credentialResponse => {
console.log(credentialResponse);
}}
onError={() => {
console.log('Login Failed');
}}
/>;
从回复中我收到了姓名和电子邮件,但不需要 googleID 或令牌。下面是我的调度函数
const googleSuccess = (resp) => {
let decoded = jwt_decode(resp?.credential);
const email = decoded?.email;
const name = decoded?.name;
const token = resp?.tokenId;
const googleId = resp?.googleId;
const result = { email, name, token, googleId };
dispatch(googleLogin({ result, navigate, toast }));
console.log(result);
};
我必须使用
jwt-decode
,因为我得到的响应是 JWT 令牌。 <GoogleLogin
onSuccess={(resp)=>googleSuccess(resp)}
onError={() => {
console.log("Login Failed");
}}
/>
我检查了其他方式,例如
import { useGoogleLogin } from '@react-oauth/google';
const login = useGoogleLogin({
onSuccess: tokenResponse => console.log(tokenResponse),
});
<MyCustomButton onClick={() => login()}>
Sign in with Google 🚀{' '}
</MyCustomButton>;
但在这里我没有得到姓名、电子邮件和 googleID。
有什么建议吗?
您可以通过个性化按钮进行认证获取id_token(JWT)。
useGoogleLogin
钩子将授权部分包装在新的 Google SDK 中
const googleLogin = useGoogleLogin({
onSuccess: async tokenResponse => {
console.log(tokenResponse);
// fetching userinfo can be done on the client or the server
const userInfo = await axios
.get('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
})
.then(res => res.data);
console.log(userInfo);
},
// flow: 'implicit', // implicit is the default
});
但是我建议您,因为您有后端,请使用授权代码流程,它将返回您将与后端交换以获得的代码,因为这是更安全的方式。
这里是整个讨论的来源,以及客户端和后端的
auth-code
流程示例:https://github.com/MomenSherif/react-oauth/issues/12
我发现这个网页清除了与Google身份验证流程主题相关的许多问题,特别是关于custom与标准Google按钮以及分别credential与access_token响应数据。