如何使用 express、passport 从 cookie 中检索网络令牌
How to retrieve web-token from cookie using express, passport
无法使用 passport、express 和 jsonwebtokens 访问保存到 cookie 的令牌。
我正在使用 passport 进行授权,使用 passport-jwt 来验证网络令牌。我已验证我的服务器正在发布网络令牌并在浏览器上设置 cookie,但是当我尝试使用安全路由时,它给我一条未经授权的消息。
...
// fetching from server
const response = fetch("http://localhost:5000/user/profile");
...
...
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
app.use(cookieParser("password"));
app.use("/",require("./routes/routes"));
app.use("/user",passport.authenticate("jwt",
{session:false},require("./routes/secure-routes"));
...
...
router.post("/login",async(req,res)=>{
passport.authenticate("login",{session:false},async (err,user)=>{
...
req.login(payload,{session:false},async error=>{
...
const token = jwt.sign(JSON.stringify(payload),"password");
res.cookie("jwt",token,{httpOnly:true});
res.status(200).send({msg:"cookie set!});
}}
})
...
...
const JWTstrategy = require("passport-jwt").Strategy;
passport.use(
new JWTstrategy(
{
jwtFromeRequest: req=>req.cookies.jwt,
secretOrKey: "password"
},
(jwtPayload, done) => {
return done(null,jwtPayload);
}
)
...
服务器确实将浏览器上的 cookie 设置为 webtoken,但由于某种原因,我无法从 GET 路由中检索到令牌。任何帮助将不胜感激。
您需要包含 cookie。
const response = fetch("http://localhost:5000/user/profile", {
credentials: "include"
});
无法使用 passport、express 和 jsonwebtokens 访问保存到 cookie 的令牌。
我正在使用 passport 进行授权,使用 passport-jwt 来验证网络令牌。我已验证我的服务器正在发布网络令牌并在浏览器上设置 cookie,但是当我尝试使用安全路由时,它给我一条未经授权的消息。
...
// fetching from server
const response = fetch("http://localhost:5000/user/profile");
...
...
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
app.use(cookieParser("password"));
app.use("/",require("./routes/routes"));
app.use("/user",passport.authenticate("jwt",
{session:false},require("./routes/secure-routes"));
...
...
router.post("/login",async(req,res)=>{
passport.authenticate("login",{session:false},async (err,user)=>{
...
req.login(payload,{session:false},async error=>{
...
const token = jwt.sign(JSON.stringify(payload),"password");
res.cookie("jwt",token,{httpOnly:true});
res.status(200).send({msg:"cookie set!});
}}
})
...
...
const JWTstrategy = require("passport-jwt").Strategy;
passport.use(
new JWTstrategy(
{
jwtFromeRequest: req=>req.cookies.jwt,
secretOrKey: "password"
},
(jwtPayload, done) => {
return done(null,jwtPayload);
}
)
...
服务器确实将浏览器上的 cookie 设置为 webtoken,但由于某种原因,我无法从 GET 路由中检索到令牌。任何帮助将不胜感激。
您需要包含 cookie。
const response = fetch("http://localhost:5000/user/profile", {
credentials: "include"
});