Any complete example for express-jwt? [closed]

删除回忆录丶 提交于 2019-11-28 08:37:30

问题


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?


回答1:


This was asked way back, just replying here if that could help someone who comes here searching - good example of express-jwt can be found at

https://hptechblogs.com/using-json-web-token-for-authentication/

and I have also tried somewhat similar implementation which can be found at -

https://github.com/Abhay-Joshi-Git/jwt-node-react/blob/master/server/index.js




回答2:


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

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 express-jwt 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.



来源:https://stackoverflow.com/questions/46364199/any-complete-example-for-express-jwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!