无法访问受保护的资源,即使成功登录后(护照oauth2.0谷歌登录)

6tqwzwtp  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(113)

使登录用户可以访问受保护的资源面临困难(oauth2 google passport.js)
我可以登录,然后被重定向到受保护的页面(在前端)。
但是当页面呈现时,我向名为/login/success的API中的一个路由发送一个请求,在那里我发送一些用户详细信息作为响应,但在此之前,我检查req.isAuthenticated是否存在,显然它存在于谷歌登录后回调URL的路由中,(callback - ive named it {AUTHOND_BASE_URL}/authorize)重定向(req.user和req.isAuthenticated),但它似乎不存在于任何其他路由中,我现在很困惑,我是一个菜鸟,所以我不知道我是否应该运行护照。在所有受保护的路由逻辑之前验证中间件,或者只做一次-
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错误

quhf5bfb

quhf5bfb1#

所以我在发送请求时没有将withCredentials设置为true,因为请求中不包含cookie

相关问题