How to retrieve web-token from cookie using express, passport
无法使用通行证,快递和jsonwebtokens访问保存在cookie中的令牌。
我正在使用通行证进行授权,并使用passport-jwt对网络令牌进行身份验证。我已验证我的服务器正在发布Web令牌并在浏览器上设置cookie,但是当我尝试使用安全路由时,它会给我发送未经授权的消息。
1 2 3 4 | ... // fetching from server const response = fetch("http://localhost:5000/user/profile"); ... |
1 2 3 4 5 6 7 8 | ... 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")); ... |
1 2 3 4 5 6 7 8 9 10 11 12 | ... 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!}); }} }) ... |
1 2 3 4 5 6 7 8 9 10 11 12 13 | ... 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。
1 2 3 | const response = fetch("http://localhost:5000/user/profile", { credentials:"include" }); |