登录用户无法访问受保护资源(oauth2 google Passport.js)时遇到问题
我能够登录,然后重定向到受保护的页面(在前端)。
但是当页面呈现时,我向 api 中名为 /login/success 的路由发送请求,其中我发送一些用户详细信息作为响应,但在此之前我检查 req.isAuthenticated 是否存在,显然它存在于谷歌登录后的回调网址,(回调-ive将其命名为{BACKEND_BASE_URL}/authorize)重定向(req.user和req.isAuthenticated),但它似乎不存在于任何其他路由中,我现在很困惑,我是菜鸟,所以我不完全知道是否应该在所有受保护路由中的逻辑之前运行 Passport.authenticate 中间件,或者是否应该只执行一次 ---
https://github.com/DAObliterator/oauth2_googlesigin..。这是该项目的链接。
流量
/*{CLIENT_URL}/authenticate -> (NOTE - via an anchor tag does not work when i send a get request using axios when click event is fired , throws a NO ACCESS CONTROL ORIGIN on the requested header error at the client side , had to sit a whole day to figure out that anchor tags has to be used to prevent CORS error )*/
//{BACKEND_URL}/login ->
app.get(
"/login",
passport.authenticate("google", { scope: ["email", "profile"] })
);
//Auth Server (google) ->
//{BACKEND_URL}/authorize->
app.get(
"/authorize",
passport.authenticate("google", {
successRedirect: "/protected",
failureRedirect: "/auth/failure",
})
);
//onSuccess
//{BACKEND_URL}/protected->
app.get("/protected", async (req, res) => {
console.log("user-details-2 ", req.user);
if (req.user) {
return res.redirect(\${process.env.CLIENT_URL}protectedPage`);`
} else {
return res.redirect(\${process.env.CLIENT_URL}authenticate`);`
}
});
//{CLIENT_URL}/protectedPage
import React , { useState , useEffect } from 'react';
import axios from "axios";
export const ProtectedPage = () => {
const [text , setText ] = useState("");
const [access, setAccess] = useState(false);
useEffect(() => {
axios.get("http://localhost:6046/login/success").then((response) => {
console.log(response.data , "response data from /protected \n");
setAccess(true);
setText(response.data.user.displayName);
}).catch((error) => {
console.log(error , ' error happened while trying to access protectedResource endpoint')
})
},[])
const handleLogout = () => {
axios.get("http://localhost:6046/logout")
}
return (
<div id="Main" className="w-screen h-screen flex flex-col">
Hello to ProtectedPage <br /> you are{" "}
{access ? text + " and is permitted " : "not-permitted"} to view the protected Resource
{access && (
<button
id="Logout-btn"
className="bg-blue-400 h-16 w-40"
onClick={handleLogout}
>
logout
</button>
)}
</div>
);
}
//{BACKEND_URL}/login/success
app.get("/login/success", (req, res) => {
if (req.isAuthenticated()) {
// If the user is authenticated, respond with user information
res.status(200).json({
error: false,
message: "Successfully Logged In",
user: req.user,
});
} else {
// If the user is not authenticated, respond with an error
res.status(403).json({ error: true, message: "Not Authorized" });
}
});
在客户端抛出403错误
所以我在发送请求时没有将 withCredentials 设置为 true ,因为 cookie 不包含在请求中