expressauthenticationpassport.jspassport-jwt

How to authenticate user at multiple routes with token generated?



authRoute.post("/login", async (req, res) => {
  const response = await AuthController.signin(req.body);
  return res.send(response);
});

authRoute.get(
  "/me",
  isAuth,
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    res.send(req.user);
  }
);

I create user authentication. But a bit of confusion here as to how to pass a token to every route. Not in query params/ URL. to authenticate the user on each router call after login.

Payload after login.


{
    "user": {
        "_id": "655307e89065578b01af1e68",
        "username": "miles214",
        "email": "miles@gmail.com",
        "password": "$2b$10$Ige5d4h05azuJKwIqDiNO.mjYkSrhRROxGEWqLLmiuftsN5NdkJPa",
        "role": "user",
        "__v": 0
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NTUzMDdlODkwNjU1NzhiMDFhZjFlNjgiLCJpYXQiOjE3MDAwNTg5NTEsImV4cCI6MTcwMDE0NTM1MX0.Ph3NXgAfQH9NVG5RBF-lrteH3frOO_A_sIuPruSCu0w"
}


Through Postman it ran as I Expected. Should I store a token in session or in local storage as it throwing unauthorized as it not getting token?

Also, I'm redirecting the user after the sign-in process.


Solution

  • You can store your token in cookies. That's how you can pass it in every request from the client side.

    Once the token shows expired send verification token request to get new auth token. That's how you can manage the session. If user does not have any verification token then redirect to the login page.