简体   繁体   中英

Node.js JWT token

I want to do an api in node.js using a token jwt.

  1. I have a user who logs in with a login and password, after successful login I generate a token which I write into the database for this user.
  2. If a given user sends a request eg GET /basic-data I have to do middleware which will check if the token in the header is the same as the one in the database.

Do I get it right?

This answer aims to just touch on the high level basics about how JWT are typically used in web applications. You said:

after successful login I generate a token which I write into the database for this user.

You are correct that after a successful login your Node application should generate a new JWT, but it is not typical to write this into a database. The whole point of using JWT is to remove as much state as possible from the server side and push it out to the clients using the application. Storing session state in the database is not ideal, for many reasons, including that database access tends to be very flow, as compared to an alternative such as a cache.

Next you asked:

If a given user sends a request eg GET /basic-data I have to do middleware which will check if the token in the header is the same as the one in the database.

In a perfect world, you would only need to check the expiry ( exp ) claims of an incoming JWT, for each request, to decide whether or not to honor the request. You would not need to check a database. In practice, you might have to maintain a whitelist or blacklist cache of JWT, but ideally the memory footprint of any cache would be small, and access time would be very fast.

No, you are not utilizing the JWT token what it is made for. You don't need to store the JWT token in the database. The token you generate comes with an expiry time that you specify while creating the token. You just need to use the predefined function(which is available in the jwt library) to verify if the token is valid and the payload consists the authenticated data.

To check the authenticity of the payload you can write a policy which would check the token when the URL is hit and then forward the request for further processing.

For example you can dump the user data in the jwt payload while creating the jwt token and once you get the token in any request, you could check if the resource is requested by an authenticated user( ex: user role = admin or vendor) by looking into your user database. The policy would work as a middleware here.

Why to store JWT in database.How you find that the same user is sending this token to which you have provided. You can verify the token by using its verify() method and then check the decoded user detail in your database for validity of that user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM