[英]express session and passport: req.isAuthenticated() return false after login
[英]req.isAuthenticated() returns true only after passport.authenticate. Any other route will return false value
這是我的注冊路線:
(我使用護照本地貓鼬)
router.post("/register", (req,res)=>{
console.log(req.body);
User.register({
username: req.body.username,
mail: req.body.email
}, req.body.password, (err, user)=>{
err ? console.log(err) : passport.authenticate("local")(req, res, () => {
console.log(user.username + " registered and logged in.");
// console.log(user);
res.send(req.isAuthenticated());
console.log(req.user);
})
})
});
創建用戶並通過身份驗證后,一切都很好。 我有 req.user object,我將 isAuthenticated 設置為 true(我嘗試以 1 秒的間隔記錄它 - 始終返回 true)。 但是,如果我嘗試從一些不同的路線檢查用戶是否經過身份驗證,例如:
router.get("/getUser", (req, res)=>{
res.send(req.user);
console.log(req.isAuthenticated());
})
我立即在控制台中得到錯誤並且從 req.user 中未定義。 有任何想法嗎? 看起來問題是 - 身份驗證后對服務器的任何請求都會刪除 req.user
遲到的答案,但我昨天遇到了同樣的問題,需要努力學習,因為這里沒有答案:)。
如果您在發送請求時通過添加: { withCredentials: true }
未指定它,您的前端 cookie 不會得到更新,並且您必須在注冊/登錄 POST 路由上執行此操作
費:
await axios.post("http://localhost:3001/register", payload, { withCredentials: true } )
但是對於 go 來說,你必須在你的服務器上傳遞一些 cors 選項:
const corsOptions = {
origin: "http://localhost:3000", // notice origin won´t work as any (*) from that point
credentials: true,
"Access-Control-Allow-Credentials": true
};
app.use(cors(corsOptions));
'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.