Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any complete example for express-jwt? [closed]

I want to use express-jwt in my express node application but I can not find any examples which demonstrate signing-in part.

Any help please?

like image 824
Saro Avatar asked Sep 22 '17 11:09

Saro


1 Answers

I would recommend that you try 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 username 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.

For jwt-express you obviously need to install the package (same as with jsonwebtoken) like:

npm install jwt-express --save

then initialize it like:

var jwt = require('jwt-express');
app.use(jwt.init('secret'));

from the docs:

The jwt.init() function returns a middleware function for Express so it must be called inside app.use(). It will automatically read in the JWT from either the cookie or the Authorization header (configured by you) and add a JWT object to the Request object (req). It will also add the jwt() method to the Response object (res) to create / store JWTs. jwt.init() must be called before any other jwt method.

These are you options:

  • cookie: (string) The name of the cookie (default: 'jwt-express')
  • cookieOptions: (object) Options to use when storing the cookie (default: {httpOnly: true})
  • cookies: (boolean) If true, will use cookies, otherwise will use the Authorization header (default: true)
  • refresh: (boolean) Indicates if the JWT should be refreshed and stored every request (default: true)
  • reqProperty: (string) The property of req to populate (default: 'jwt')
  • revoke: (function) jwt.revoke() will call this function (default: function(jwt) {})
  • signOptions: (object) Options to use when signing the JWT (default: {})
  • stales: (number) Milliseconds when the jwt will go stale (default: 900000 (15 minutes))
  • verify: (function) Additional verification. Must return a boolean (default: function(jwt) {return true})
  • verifyOptions: (object) Options to use when verifying the JWT (default: {})

The rest of the logic is up to you to code, but my examples should give you a fair idea how to manage jwt's in your application..

Here is an example how I implemented jwt via jsonwebtoken:

 // 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 assign 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.

like image 175
iLuvLogix Avatar answered Oct 10 '22 05:10

iLuvLogix