2

I'm new to JWT which stands for Json Web Token. I've confused with couple of its terms: Access Token and Refresh Token.

purpose: I wanna implement a user authorization which logs the user out after two hours of being idle (don't request the site or exit from the browser).

To reach that goal I'm trying to follow the below items:

  1. After the user registers/logs-in in the site, I create Access Token and Refresh Token.
  2. Save the refresh token in the DB or cookie.
  3. After 15 minutes the users token the access token expired.
  4. In case of a user being idle for 2 hours, I remove the refresh token from the cookie or DB, else I renew the access token using refresh token.

Is there any optimized way to reach that purpose?

Mostafa Ghadimi
  • 5,883
  • 8
  • 64
  • 102

1 Answers1

1

First of all u need to understand the principle of JWT's and how they are passed between server and client and matched server-side against a secret - here's the doc

enter image description here

The payload can be any arbitrary user data - i.E.: just a usrname or id

Basically you need a service that generates a token on successful authentication (when the user logs in with the proper credentials, i.E.: usr & pwd) and create an additional header with the token to be used in further requests to the server.

 // INFO: Function to create headers, add token, to be used in HTTP requests
  createAuthenticationHeaders() {
    this.loadToken(); // INFO: Get token so it can be attached to headers
    // INFO: Headers configuration options
    this.options = new RequestOptions({
      headers: new Headers({
        'Content-Type': 'application/json', // INFO: Format set to JSON
        'authorization': this.authToken // INFO: Attach token
      })
    });
  }

  // INFO: Function to get token from client local storage
  loadToken() {
    this.authToken = localStorage.getItem('token');; // Get token and asssign to 
variable to be used elsewhere
  }

and some functionality to store the user-status i.E.:

 // INFO: Function to store user's data in client local storage
 storeUserData(token, user) {
   localStorage.setItem('token', token); // INFO: Set token in local storage
   localStorage.setItem('user', JSON.stringify(user)); // INFO: Set user in local 
  storage as string
      this.authToken = token; // INFO: Assign token to be used elsewhere
      this.user = user; // INFO: Set user to be used elsewhere
    }

and a logout function to destroy the token in the local storage, i.E.:

 // INFO: Function for logging out
 logout() {
this.authToken = null; // INFO: Set token to null
   this.user = null; // INFO: Set user to null
   localStorage.clear(); // INFO: Clear local storage
 }

In case you use npm's jsonwebtoken, you can set the ttl of the token when generating it:

const token = jwt.sign({ id: idDB }, "secret", { expiresIn: '24h' }); 

or whatever ttl you desire, the string "secret" refers to the secret that's matched against the server.

btw: If I understand you correctly, your points number 3 and 4 contradict each other..

  1. After 15 minutes the users token the access token expired.
  2. In case of a user being idle for 2 hours, I remove the refresh token from the cookie or DB, else I renew the access token using refresh token.

in case 4 it will be destroyed anyways in 15 mins if you implemented the logic of number 3 correctly

iLuvLogix
  • 5,920
  • 3
  • 26
  • 43
  • I didn't understand how your code logs-out the user after two hours of being idle. I mean if the user didn't send any request to the server for two hours, after this period of time, whenever the user send a request, it should be logged out. I think `expiresIn` would act a bit different, because it just considers the time that the token is generated. **NOTE**: Some browsers don't support localStorage. – Mostafa Ghadimi Aug 06 '18 at 11:12
  • 1
    the ttl on generating the token does that for you, in my case its 24h - but you can also declare it like this in seconds*mins: **const token = jwt.sign({ id: idDB }, "secret", { expiresIn:60*15 });** – iLuvLogix Aug 06 '18 at 11:39
  • you mean that I don't need to renew the access token? – Mostafa Ghadimi Aug 06 '18 at 11:42
  • 1
    why do you want to do that? after being expired you use the router to redirect the user to your login page and on a new, successful login, a new token will be generated and passed around - you dont reuse the old token, you generate a new one.. – iLuvLogix Aug 06 '18 at 11:44
  • I can't distinguish access token from refresh token and don't know their usage. – Mostafa Ghadimi Aug 06 '18 at 11:47
  • 1
    according to what you are trying to implement you only need three functions: **jwt.sign** to generate the token, **jwt.verify** to match a token and **this.authToken = null & localStorage.clear();** to destroy it.. – iLuvLogix Aug 06 '18 at 11:55
  • how about some cases that browsers don't support localStorage? – Mostafa Ghadimi Aug 06 '18 at 11:56
  • 1
    you could use a cookie, your browsers local storage or for example use a database and retrieve it on each request, match or change from there - but i wouldn't recommend that - here's a [link](https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage) you should read.. – iLuvLogix Aug 06 '18 at 12:00