我想使用 Firebase 实现 Google Oauth 登录并保持登录状态,即使用户刷新页面。
signInWithRedirect
重定向到Google登录页面,但getRedirectResult
在成功登录后无法检索用户身份验证信息。
什么问题?然后,教我如何在 nextjs 13 或 React 中即使用户刷新页面也保持登录状态。
"use client";
import { useState, useEffect } from "react";
import { getAuth, signInWithPopup, GoogleAuthProvider, signInWithRedirect, getRedirectResult } from "firebase/auth";
import { app } from "../../firebase_config";
import { useAuth } from "./AuthContext";
import { FcGoogle } from "react-icons/fc";
import s from "./Login.module.css";
export default function Login() {
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
const [user, setUser] = useState(null);
const { isLoggedIn, login, logout } = useAuth();
const handleGoogleSignIn = async () => {
signInWithRedirect(auth, provider)
.then(async (result) => {
const credential = GoogleAuthProvider.credentialFromResult(result);
const user = result.user;
console.log(result);
console.log(credential);
setUser(user);
login();
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
})
.finally(() => {
getRedirectResult(auth).then((result) => {
console.log(result);
});
});
};
return (
<div>
{isLoggedIn ? (
<div className={s.userProfile}>
<img className={s.userImg} src={user.photoURL}></img>
<span>{user.displayName}</span>
</div>
) : (
<button onClick={handleGoogleSignIn}>
<FcGoogle style={{ fontSize: "em" }} />
Login
</button>
)}
</div>
);
}
我确认弹出登录方法工作正常,但我想使用重定向方法。
signInWithRedirect
导航离开您的应用程序,因此您需要在单独的函数中调用 getRedirectResult
,以便在页面重定向回来时获得响应。
const { isLoggedIn, login, logout } = useAuth();
useEffect(() => {
getRedirectResult(auth)
.then((result) => {})
.catch((error) => {});
}, []);
... rest of your code