简体   繁体   中英

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

Can't access token saved to cookies using passport, express and jsonwebtokens.

I'm using passport for authorization and passport-jwt to authentication of web-tokens. I have verified that my server is issuing web-tokens and setting cookies on the browser, but when I attempt to use secure routes it gives me an unauthorized message.

  ...
  // 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);
       }
    )
   ...

The server is definitely setting the cookies on the browser to the webtoken, but for some reason I can't retrieve the token from the GET route. Any help would be greatly appreciated.

You need to include the cookies.

  const response = fetch("http://localhost:5000/user/profile", {
      credentials: "include"
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM