preface

In daily work, we will inevitably encounter the use of Token scenarios, generally speaking, the background gives us a Token, we store this Token in the local, each request to carry, but what problems will exist in this?

Applets scenario

Handling method after the Token expires

If we now have the Token stored in the applet, each request will be returned with a Token from the background:

Generally speaking, there may be expired behavior of Token, so we also want to discuss how to deal with Token after expiration.

The stupidest solution would be to let the user log in again after the token expires and then regenerate the token, but obviously that’s a bad experience!

In fact, we can obtain a new token after the token expires, and finally help the user to request the interface that failed before. We call this mechanism a secondary retransmission mechanism

When does expiration cause problems?

For the server, the vast majority have to carry the token, the token once date means that the interface might be attempt failed, let’s consider a more extreme case, if the token is valid for 1 hour, then this token corresponding user has been in this one hour access (during this period is too small no exit program). Then at 59 minutes and 59 seconds he took his just valid for only one hour of token request to the server, because HTTP is time consuming, after the service side should be already expired, then the server after the overdue token will access denied, says this token has expired, that this time will give the user a very bad experience, I believe that the problem extended here, we should have their own solution, then let’s talk about the above secondary retransmission mechanism how to achieve?

Secondary retransmission mechanism

The secondary reissue mechanism is designed to give the user the best user experience (refresh the token automatically without any awareness, not login again).

In fact, it is also very easy to implement, the general idea is:

The Api of each request is stored and a new token is obtained after the token is invalid. Then the failed Api is re-requested according to the stored requested Api status

The pseudocode is as follows (for reference only) :

_request(url, resolve, reject, data = {}, method = 'GET', noRefetch = false) {
    wx.request({
      url: api.url,
      method: method,
      data: data,
      header: {
        Authorization: wx.getStorageSync('token');
      },
      success: (res) = > {
        const code = res.statusCode
          if (code === 403) {
            if(! noRefetch) { _refetch( url, resolve, reject, data, method ) } } } }) }_refetch(. param) {
    getTokenFromServer((token) = > {
      this._request(... param,true);
    });
  }
Copy the code

Something like the flow chart belowSince the small program does not need an account password and is supported by wechat’s official login interface, it is ok for us to do so. What about ordinary Web applications?

The access_token and refresh_token dual tokens implement non-aware login

In ordinary web page in the application development and back-end gives us a token, we save, each request validation to carry, and just small program examples (extreme), token expires, because we don’t have a user account password, there is no way to make the background to generate a token, because the background don’t know who you are, When the user logs in, we can save the user’s account password and then send it to the server to obtain a new token. This can solve the problem, but it has a high security problem, so what other way is there?

In fact, we use the double token mechanism above the headline

access_token

What is the access_token? It authenticates the user, passes it to the back end, and the back end tells you whether the access_token is valid

refresh_token

How to understand the refresh_token? It works as a refresh, so it avoids having the user re-enter the account and password for re-authentication,

So how do these two work together?

If we encounter an expired access_token, then we need to use refresh_token to get a new access_token. Sounds simple, but now what if refresh_token also expires? If it expires, we can only ask the user to enter the account password again for strong authentication, which will disturb the user again. Then we will talk about how to properly coordinate the double token:

The correct way is that both tokens have their own expiration time, because the access_token needs to be refreshed, so the expiration time of refresh_token is longer than that of access_token. So how do you keep refresh_token from expiring? The solution is that after refresh_token is refreshed by using refresh_token, the expiration time of refresh_token is also extended.

Generally we can set the expiration time of access_token to 2 hours, refresh_token to 1 month, and then the user comes in for the first time and uses the access_token to expire. After the expiration, the front end carries the refresh_token to obtain a new access_token, and the new access_token returned is still 2 hours. In addition, the refresh_token itself is refreshed again, and the expiration time after refreshing is still 1 month (no accumulation). This ensures that users can enjoy a non-perceptive experience as long as they visit the app for a month,

In other words, if the user never open our application of a month, so let’s don’t need to let him continue to enjoy the user experience, first of all to ensure the safety of his account, so let him enter account password for strong authentication (I believe you should have when using some app encountered this kind of situation, this big probability is the use of the dual token mechanism).

conclusion

This is a relatively complete token and user experience solution, you can have other ideas and views in the comments section!