I'll show you why you don't need to log in every time you use Taobao, jd.com, etc?

background

Nowadays, everyone has mobile phones, which are smart phones such as apple and Android;

Nowadays, everyone loves online shopping, which are e-commerce platforms such as Taobao and jd.com.

If you like online shopping, do you find that if you download Taobao Jingdong, you don't have to log in as long as you use it from time to time.

Why?

From a technical point of view, when users have used the platform within a certain period of time, they can not log in again, but it must be noted that they must log in for the first time. If users do not use it for a certain period of time, they must log in again. This method is called Double token.

Flow diagram

The details are as follows:

  • 1. Download the software as needed and complete the account registration
  • 2. Log in to the account, and the back end returns two token information, namely access_token and refresh_token,access_ A token is called a short token, refresh_ A token is called a long token
  • 3. Short token is access_ The token has not expired, all requests are normal, and the user can return whatever data he needs
  • 4.access_ When the token expires, the server returns a status code to the client. After receiving the status code, the client uses refresh_token gets a new access again_ Token and refresh_token, which is equivalent to resetting the token
  • 5. If in refresh_ The software has not been used during the validity period of the token, which means refresh_ When the token expires, use it to get new access_token and refresh_ When token, a new status code will be returned, prompting that the user must log in

Some people may have this question: Why are you using refresh_ When token, return a new access_token and refresh_token instead of extending the original refresh_ How long is the token valid?

  • For safety, if once refresh_ If the token is intercepted by hackers and other personnel, they can always illegally use your account
  • Even if it is intercepted, as long as the user refreshes, it will get a new refresh again_ Token, then the previously intercepted refresh_ The token will be invalid

Time setting of token

The time setting of token needs to be divided according to the requirements, and the settings are different:

PC network application

For network applications, since the token can be obtained directly and intuitively, the expiration time of both accessToken and refreshToken should not be set too long for security reasons, and the token needs to be changed constantly. Therefore, the accessToken of PC network applications is generally set to expire in 2h, while the refreshToken is set to expire in 1-2 days, Less than one day is OK. If the setting time is short, refresh the freshToken frequently during the active period. If the setting time is long, only set a threshold (for example, set a 6day threshold for the refreshToken of 7day s). Refresh the refreshToken when the refreshToken is less than or equal to this threshold.

Mobile application

For mobile APP applications, the login operation is usually done only once, so the expiration time of the token must be unlimited, that is, it will not expire. However, for security reasons (such as preventing you from losing your mobile phone), The token should be visible to the user to some extent (for example, after checking the identity in the security center, you can see which devices have tokens, that is, which devices will be allowed to log in) and allow the user to operate them to some extent (for example, if you lose your mobile phone, log in to the security center and remove the token of that mobile phone, that is, remove the login permission of that mobile phone, so as to force your account on the application of that mobile phone offline)

Processing of invalid Token

For frequently replaced tokens, the following ideas are provided on how to deal with old, unexpired and invalid Token s:

1) Simply remove the token from the browser

Obviously, this method is useless for server security, but it can prevent the attacker by removing the existing token (for example, the attacker must steal the token before the user goes offline)

2) Make a token Black / white list

After removing the tokens stored in the browser, if you want to be more strict, you can only make a black / white list of invalid but not expired tokens on the server, operate the database to match the tokens in each request, and maintain them in some way (whether it is the regular deletion and maintenance of the blacklist or the deletion and maintenance of the white list when it is invalid), However, obviously, this method still violates the original intention of token statelessness, but there is no other way.

The storage can be stored in the database in the way of userId token (of course, you can also add other fields to indicate other information as you like, such as mac address, mobile phone or computer, device model, balabalabalabalabala... Etc.). In the case of white list, valid tokens can be stored directly, Delete the specified token in the logic that requires the token to be invalid (for example, delete the old invalid but not expired token when refreshing the token). If it is a blacklist, you need to delete the expired tokens on a regular basis.

In addition to matching in the database list, the verification also needs to verify the validity of the token itself.

3) Just set the expiration time of the token to be short enough

How to refresh Token (quoted from github)

static refreshToken = (token): string => {
    let optionKeys = ['iat', 'exp', 'iss', 'sub'];
    let newToken;
    let obj = {};

    let now = Math.floor(Date.now()/1000);
    let timeToExpire = (token['exp'] - now);

    if (timeToExpire < (60 * 60)) { //1h
        for (let key in token) {
            if (optionKeys.indexOf(key) === -1) {
                obj[key] = token[key];
            }
        }

        let options = {
            expiresIn: '7 days',
            issuer: 'moi',
            subject: token.sub,
            algorithm: 'HS256'
        };

        newToken = JWT.sign(obj, Config.get('/jwtSecret'), options);
    }
    else {
        newToken = '';  //no need to refresh, do what you want here.
    }

    return newToken;
}

Another idea of refreshing refresh Token (official website)

/**
 * Example to refresh tokens using https://github.com/auth0/node-jsonwebtoken
 * It was requested to be introduced at as part of the jsonwebtoken library,
 * since we feel it does not add too much value but it will add code to mantain
 * we won't include it.
 *
 * I create this gist just to help those who want to auto-refresh JWTs.
 */const jwt = require('jsonwebtoken');

function TokenGenerator (secretOrPrivateKey, secretOrPublicKey, options) {
  this.secretOrPrivateKey = secretOrPrivateKey;
  this.secretOrPublicKey = secretOrPublicKey;
  this.options = options; //algorithm + keyid + noTimestamp + expiresIn + notBefore
}

TokenGenerator.prototype.sign = function(payload, signOptions) {
  const jwtSignOptions = Object.assign({}, signOptions, this.options);
  return jwt.sign(payload, this.secretOrPrivateKey, jwtSignOptions);
}

// refreshOptions.verify = options you would use with verify function
// refreshOptions.jwtid = contains the id for the new token
TokenGenerator.prototype.refresh = function(token, refreshOptions) {
  const payload = jwt.verify(token, this.secretOrPublicKey, refreshOptions.verify);
  delete payload.iat;
  delete payload.exp;
  delete payload.nbf;
  delete payload.jti; //We are generating a new token, if you are using jwtid during signing, pass it in refreshOptions
  const jwtSignOptions = Object.assign({ }, this.options, { jwtid: refreshOptions.jwtid });
  // The first signing converted all needed options into claims, they are already in the payload
  return jwt.sign(payload, this.secretOrPrivateKey, jwtSignOptions);
}

module.exports = TokenGenerator;

Test module:

/**
 * Just few lines to test the behavior.
 */

const TokenGenerator = require('./token-generator');
const jwt = require('jsonwebtoken');

const tokenGenerator = new TokenGenerator('a', 'a', { algorithm: 'HS256', keyid: '1', noTimestamp: false, expiresIn: '2m', notBefore: '2s' })
token = tokenGenerator.sign({ myclaim: 'something' }, { audience: 'myaud', issuer: 'myissuer', jwtid: '1', subject: 'user' })
setTimeout(function () {
  token2 = tokenGenerator.refresh(token, { verify: { audience: 'myaud', issuer: 'myissuer' }, jwtid: '2' })
  console.log(jwt.decode(token, { complete: true }))
  console.log(jwt.decode(token2, { complete: true }))
}, 3000)

About Python technology reserve

It's good to learn Python well, whether in employment or sideline, but to learn python, you still need to have a learning plan. Finally, let's share a full set of Python learning materials to help those who want to learn Python!

1, Python learning routes in all directions

All directions of Python is to sort out the commonly used technical points of Python and form a summary of knowledge points in various fields. Its purpose is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2, Learning software

If a worker wants to do well, he must sharpen his tools first. The commonly used development software for learning Python is here, which saves you a lot of time.

3, Getting started video

When we watch videos, we can't just move our eyes and brain without hands. The more scientific learning method is to use them after understanding. At this time, the hand training project is very suitable.

4, Actual combat cases

Optical theory is useless. We should learn to knock together and practice, so as to apply what we have learned to practice. At this time, we can make some practical cases to learn.

5, Interview materials

We must learn Python in order to find a high paying job. The following interview questions are the latest interview materials from front-line Internet manufacturers such as Alibaba, Tencent and byte, and Alibaba boss has given authoritative answers. After brushing this set of interview materials, I believe everyone can find a satisfactory job.


This complete set of Python learning materials has been uploaded to CSDN. Friends can scan the official authentication QR code of CSDN below on wechat and get it for free [guaranteed to be 100% free]

Keywords: Python Programmer crawler

Added by rami103 on Tue, 15 Feb 2022 08:26:24 +0200