How to use koa-jwt

  node.js, question

I now want to do a user authentication login function.

The front-end uses koa-jwt to obtain token through login calling interface, and stores the token in cookie inside after returning to the front-end.

Then all ajax requests from the front end will pass this token to the back end in header inside.

Now back-end verification here I don’t know what to do.

The backend can now get the token from the frontend through headers. But how should we judge whether the current token is invalid?

My idea is to pass

if (!  this.request.headers.token) {this.throw(401, 'Authorization required');  bracket

To judge. However, it seems that it is impossible to judge whether token is invalid.

May I know how to use koa-jwt? There seem to be few examples online. I don’t know how to use it.

First of all, you should knowkoa-jwtThe function of the, currently only providesdecode,signAndverifyThe function of, you said judgmenttokenpast duekoa-jwtThe module does not specifically provide a function to validate.

2. How to judgetokenIs it overdue? First, let me introduce you briefly.jwt, and then teach you how to judge expired.

2.1jwtbrief introduction

JSON Web Token(jwt) In web pages, many operations need to verify the user’s rights and judge whether the user logs in or not. There are generally two ways to achieve this: one is throughsessionAndcookie; The other is authenticationtoken. utilizetokenThere are two main advantages to authentication.

  • The server does not need to request DB to obtain user information, because user information already exists in token.

  • The token authentication method is also applicable to the mobile terminal and the PC terminal, and the server does not need to maintain two sets of authentication mechanisms.

A standard jwt consists of 3 parts<header>,<payload>And<signature>

  • Header: base64 encoded json object, including encryption algorithm used, etc.

  • Payload: base64 encoded json object that stores user-related information.

  • Signature: A signature string generated according to Header, PayloadA and a key (only known by the server) and using the encryption algorithm specified in Header.

2.2 How to Judge Failure

There are many ways to judge the expiration of token. here are some for you to choose from.

  • Jwt provides expired parameter settings, which are set in Payload when issuing token (when koa-jwt calls sign)expProperty, which is provided by jwtRegistered Claims(Reservation Statement), remember that it must be larger than the current time, for example, it expires 10 minutes after the current time is set.

 Now () plus 10*60*1000,

Then you canPersistenceStored in your localstorage, sessionStorage or cookie, this token is sent to the server through the request and will be reported when it is verified (when koa-jwt is called to verify)TokenExpiredError

Thrown error if the token is expired.
 Error object:
 - name: 'TokenExpiredError'
 - message: 'jwt expired'
 - expiredAt: [ExpDate]
  • After the server generates a token, you can store the token in a cookie (or sessionStorage) in the requested return, and then set the expiration time of the cookie.expireIn this way, the next time you are requested in your requestheaderOr ..bodyWhen you can’t get the token inside, you will know that the token has expired (similar to the code you provided, but remember to set the expiration time of this cookie that stores the token).

  • Custom similarexpBecauseexpIs to retain the attribute, so you can set oneorigin-iatLast issued time, and then persistent storage, after solving the token, determine the current time andorigin-iatHas the time difference reached your expiration time, and when it does, re-request authentication and re-issue token with the following pseudocode

var profile = jwt.verify(req.header.token || req.body.token, secret);
 // if more than 7 days old, force login
 if (Date().now() - profile.original_iat  > 7 * 24 * 60 * 60 * 1000) { // iat == issued at
 return res.status(401).json({ isError: true, error: { message: 'Access Forbidden'}});  // re-logging

The difference between these methods is that the first and third methods can obtain the token all the way through the request, but the token may be expired. The second way is that token may not be obtained by request. You can make appropriate choices according to your business needs.

Attached:JSON Web Token Specification RFC 7519