Any complete example for express-jwt? [closed] Any complete example for express-jwt? [closed] express express

Any complete example for express-jwt? [closed]


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 soit must be called inside app.use(). It will automatically read in theJWT from either the cookie or the Authorization header (configured byyou) and add a JWT object to the Request object (req). It will alsoadd the jwt() method to the Response object (res) to create / storeJWTs. 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.