Ale*_*aga 6 authentication node.js google-oauth reactjs
在 Google 身份验证成功后,我需要返回一些信息以供 React 使用,从而允许访问客户端上的私有路由,就像我使用本地策略登录所做的那样({isAuthenticated: true}发送到 React,React 使用此信息来设置由私有路由包装器组件读取的自定义挂钩的状态,以检查用户是否可以访问应用程序的主页;否则用户将被发送回登录页面)。
但是,由于我需要将用户重定向到http://localhost:5000/auth/google“使用 Google 登录”React 按钮,而 Google 的身份验证路由会处理其余部分,直到将用户重定向到应用程序的主页,所以我不知道如何将其实现只需编写一个res.json像我在策略登录中所做的那样的工作local(在我的最后一次尝试中,这导致json直接发送到浏览器屏幕)。
如果有什么区别的话:我在我的服务器上使用 Passport JWT 来保护路由免受未经身份验证的请求的影响,所以我还在session: falseGoogle 上设置并在之前生成了 JWT 令牌res.redirect。下面是我/auth处理 Google 访问的路线:
auth.js
router.get(
"/google",
passport.authenticate("google", {
scope: ["email", "profile"],
})
);
const clientUrl =
process.env.NODE_ENV === "production"
? process.env.CLIENT_URL_PROD
: process.env.CLIENT_URL_DEV;
router.get(
"/google/movie-log",
passport.authenticate("google", {
failureRedirect: clientUrl + "/login",
session: false,
}),
(req, res) => {
const token = req.user.generateJWT();
res.cookie("access_token", token, { httpOnly: true, sameSite: true });
res.redirect(clientUrl + "/diary");
}
);
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
Login.js(这是React上的登录组件)
function Login() {
const authContext = useContext(AuthContext);
const navigate = useNavigate();
const { state } = useLocation();
const [message, setMessage] = useState(null);
const [userInfo, setUserInfo] = useState({
email: "",
password: "",
});
function handleInfo(event) {
const { name, value } = event.target;
setUserInfo((prevValue) => {
return {
...prevValue,
[name]: value,
};
});
}
function handleLogin(event) {
event.preventDefault();
axios
.post("/login", userInfo)
.then((response) => {
const { isAuthenticated, user, message } = response.data;
if (isAuthenticated) {
authContext.setUser(user);
authContext.setIsAuthenticated(isAuthenticated);
navigate(state?.path || "/diary");
} else {
setMessage(message);
}
})
.catch((err) => {
console.log(err);
});
}
return (
//login form - removed to clear the clutter
<GoogleButton
style={{ width: "100%" }}
onClick={(event) => {
event.preventDefault();
window.open("http://localhost:5000/auth/google", "_self");
}}
/>
);
}
export default Login;
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
| 归档时间: |
|
| 查看次数: |
947 次 |
| 最近记录: |