0

Dears,

I'm trying to use JWT tokens to authorize my user. After user and password are confirmed at database, a JWT token is created. I also made a middleware to verify that token and used that middleware at some route that I've created. Testing this route with Postman inserting the token at the header, everything worked fine, but when I'm try to use this at the browser, the token is storage in the login header after I login, but when I redirect (using res.redirect('/dashboard')) I can't access the dashboard page because the token are only at login header, and not at dashboard header.

Do you know how to make that token available at all my environment? Or what's the best way to do that routes authorizations?

Thanks a lot for your help!

Rhames Lima
  • 28
  • 1
  • 5

2 Answers2

0

You can use session or cookies and store that token in there and set a time limit of expiry on them.

Prince Agrawal
  • 380
  • 4
  • 14
  • Thanks for your help! I never worked with sessions, in fact this is my first web app. I can create a session using 'express-session' and store the token in that session. Is that correct? And if is, I must save the sessionID in some database or it is not required? – Rhames Lima Jul 29 '20 at 02:12
  • Session IDs can be stored as cookies locally at the client end. You can use a database when you have large number of users, it is considered good practice to store session in a database but not required. When a request is made to the server, the server transmits the cookie containing the session ID. – Prince Agrawal Jul 29 '20 at 02:24
  • But if the user try to use the web app in private mode, cookies by default can not be salved, right? Is there anyway to prevent this? – Rhames Lima Jul 29 '20 at 02:33
  • That's what private mode is for. In this mode browser won't store history, cookies, form data, etc. – Prince Agrawal Jul 29 '20 at 02:37
0

Use sessionStorage to make your JWT persist on your users' browsers:

sessionStorage.setItem('JWT', 'my.jwt.data');

Then, get it back using getItem:

const jwt = sessionStorage.getItem('JWT');
Andrei
  • 400
  • 2
  • 6
  • According to this (https://stackoverflow.com/questions/38495168/how-to-use-window-sessionstorage-in-node-js) I can't use sessionStorage at NodeJS. I tried and failed. Do you think there's a way to make this work with 'express-session'? – Rhames Lima Jul 29 '20 at 10:27
  • 1
    I see. Then, I understand you want to be able to access the JWT in the back end, as it should be present in `req.headers`. It's up to the Front End to send you an `authorization` header (or any similar header), most likely stored in the browser using `localStorage`, where you may access the JWT. Then, you decode it using [jwt.decode](https://www.npmjs.com/package/jsonwebtoken#jwtdecodetoken--options). – Andrei Jul 29 '20 at 20:02