当前位置:网站首页>I'll show you why you don't need to log in every time you use Taobao, jd.com, etc?
I'll show you why you don't need to log in every time you use Taobao, jd.com, etc?
2022-07-02 07:55:00 【Python crispy corner】
background
Today, , Everyone has a cell phone , All mobile phones are smart phones such as apple Android ;
Today, , Everyone loves online shopping , Online shopping are e-commerce platforms such as Taobao and JD .
If you like online shopping, do you find , Download Taobao Jingdong , As long as you use it from time to time , You don't have to log in .
Why is that ?
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 you must log in for the first time , If the user does not use it for a certain period of time , You have to log in again , This way we call it double token.
Flow diagram

The details are as follows :
- 1. Download software as needed , Complete account registration
- 2. Login account , Backend return Two token Information , Respectively access_token as well as refresh_token,access_token Call it short token,refresh_token Call it long token
- 3. short token That is to say access_token Not expired , All requests are normal , Users can return whatever data they need
- 4.access_token Be overdue , The server returns a status code to the client , After the client receives the status code , Use refresh_token Get a new one again access_token and refresh_token, It's like resetting token
- 5. If in refresh_token The software has not been used in the validity period , signify refresh_token Be overdue , Use it to get new access_token and refresh_token A new status code will be returned , Prompt that the user must log in
Some people may have such questions : Why are you using refresh_token To return a new access_token and refresh_token, Instead of extending The original refresh_token The period of validity ?
- For the sake of safety , If once refresh_token Intercepted by hackers and other personnel , They can always use your account illegally
- Even if it is intercepted , As long as the user refreshes, he will get a new one again refresh_token, So before Intercepted refresh_token It will fail.
token Time settings for
token The time setting of depends on the demand :
PC Web applications
For web applications , because token You can directly and intuitively obtain , So whether it's accessToken still refreshToken For safety's sake , The expiration time should not be set too long , And it needs to be replaced constantly token, therefore PC The development of network application accessToken Generally set as 2h Be overdue , and refreshToken Set to 1 Day to 2 The weather is better , Insufficient 1 The sky is the limit , If the setting time is short, refresh frequently during the active period freshToken Just fine , If the setting time is long , Just set a threshold ( such as 7day Of refreshToken Set up a 6day threshold ), stay refreshToken Refresh when it is less than or equal to this threshold refreshToken Just fine .
Mobile phone application
For mobile phone APP In terms of application , The login operation is usually done only once , therefore token The expiration time of must be infinite , It will not expire , But for the sake of safety ( For example, to prevent you from losing your cell phone ),token It should be visible to the user to some extent ( For example, after checking your identity in the security center, you can see which devices have token, Which devices will be allowed to log in ) Users can operate it to a certain extent ( For example, you lost your mobile phone , Then log in to the security center to remove the mobile phone token, That is to remove the login permission of that mobile phone , So that your account on that mobile phone's application is forced to be offline )
invalid Token To deal with
For frequently replaced Token, How to deal with old, unexpired and invalid Token, Here are some ideas :
1) Simply remove from the browser token Just fine
obviously , This approach is not useful for server security , But it can be done by removing the existing token To stop the attacker ( such as , The attacker must steal before the user goes offline token)
2) Make a token black / White list
After removing the stored in the browser token If you want to be more strict , You can only create an invalid but not expired one on the server token Black / The white list , Operate the database in each request token The matching of , And maintain it in some way ( Whether it is the regular deletion and maintenance of the blacklist , Delete the white list when it is invalid ), However, it is clear that this approach still violates token Stateless original intention , But there is no other way .
Storage can be done according to userId—token Stored in a database ( Of course, you can also add other fields to indicate other information as you like , for instance mac Address , Is it a mobile phone or a computer , Equipment model , Balabalabala ····), White list words are directly stored in effective token, The need to token Remove the specified... From the invalid logic token that will do ( For example, refresh token Delete the old ones that are invalid but not expired ). If it is a blacklist, you need to delete the expired ones regularly token 了 .
In addition to matching in the database list, verification is also required token Its own effectiveness .
3) Only need to token The expiration time of is set short enough
How to refresh Token( Quote 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;
}
Refresh refresh Token Another way of thinking ( 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
Learn from good examples Python Whether it's employment or sideline, it's good to make money , But learn to Python Still have a learning plan . Finally, let's share a complete set of Python Learning materials , For those who want to learn Python Let's have a little help !
One 、Python Learning routes in all directions
Python All directions are Python Sort out the common technical points , Form a summary of knowledge points in various fields , The use of it is , You can find the corresponding learning resources according to the above knowledge points , Make sure you learn more comprehensively .

Two 、 Learning software
If a worker wants to do a good job, he must sharpen his tools first . Study Python Common development software is here , It saves you a lot of time .

3、 ... and 、 Getting started video
When we were watching videos to learn , You can't just move your eyes and brain without hands , A more scientific way to learn is to use them after understanding , At this time, the hand training program is very suitable .

Four 、 Practical cases
Optical theory is useless , Learn to knock together , Do it , Can you apply what you have learned to practice , At this time, we can make some practical cases to learn .

5、 ... and 、 Interview information
We learn Python Must be to find a well paid job , The following interview questions are from Ali 、 tencent 、 The latest interview materials of big Internet companies such as byte , And the leader Ali gave an authoritative answer , After brushing this set of interview materials, I believe everyone can find a satisfactory job .


This full version of Python A full set of learning materials has been uploaded CSDN, Friends can scan the bottom of wechat if necessary CSDN The official two-dimensional code is free 【 Guarantee 100% free 】

边栏推荐
- 【TCDCN】《Facial landmark detection by deep multi-task learning》
- Semi supervised mixpatch
- 【FastDepth】《FastDepth:Fast Monocular Depth Estimation on Embedded Systems》
- Thesis writing tip2
- 【Hide-and-Seek】《Hide-and-Seek: A Data Augmentation Technique for Weakly-Supervised Localization xxx》
- How do vision transformer work?【论文解读】
- jetson nano安装tensorflow踩坑记录(scipy1.4.1)
- Regular expressions in MySQL
- What if the laptop task manager is gray and unavailable
- 用全连接层替代掉卷积 -- RepMLP
猜你喜欢
![How do vision transformer work? [interpretation of the paper]](/img/93/5f967b876fbd63c07b8cfe8dd17263.png)
How do vision transformer work? [interpretation of the paper]

【Mixup】《Mixup:Beyond Empirical Risk Minimization》

Faster-ILOD、maskrcnn_benchmark训练coco数据集及问题汇总

Machine learning theory learning: perceptron

【多模态】CLIP模型

联邦学习下的数据逆向攻击 -- GradInversion

程序的执行

【学习笔记】Matlab自编高斯平滑器+Sobel算子求导

Correction binoculaire

Sorting out dialectics of nature
随机推荐
What if the notebook computer cannot run the CMD command
Record of problems in the construction process of IOD and detectron2
【C#笔记】winform中保存DataGridView中的数据为Excel和CSV
【Cutout】《Improved Regularization of Convolutional Neural Networks with Cutout》
【Paper Reading】
【Cascade FPD】《Deep Convolutional Network Cascade for Facial Point Detection》
One book 1078: sum of fractional sequences
win10+vs2017+denseflow编译
【学习笔记】反向误差传播之数值微分
label propagation 标签传播
CONDA common commands
[learning notes] numerical differentiation of back error propagation
Timeout docking video generation
Meta Learning 简述
open3d学习笔记四【表面重建】
Faster-ILOD、maskrcnn_benchmark训练coco数据集及问题汇总
Mmdetection trains its own data set -- export coco format of cvat annotation file and related operations
Installation and use of image data crawling tool Image Downloader
win10解决IE浏览器安装不上的问题
【BiSeNet】《BiSeNet:Bilateral Segmentation Network for Real-time Semantic Segmentation》