簡體   English   中英

如何使用快遞,護照從Cookie檢索網絡令牌

[英]How to retrieve web-token from cookie using express, passport

無法使用通行證,快遞和jsonwebtokens訪問保存在cookie中的令牌。

我使用的是用於授權的通行證,以及用於對網絡令牌進行身份驗證的passport-jwt。 我已驗證我的服務器正在發布Web令牌並在瀏覽器上設置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"
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM