当前位置:网站首页>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
】
边栏推荐
- One book 1078: sum of fractional sequences
- 【多模态】CLIP模型
- 【MnasNet】《MnasNet:Platform-Aware Neural Architecture Search for Mobile》
- CONDA common commands
- 【Random Erasing】《Random Erasing Data Augmentation》
- 程序的内存模型
- 用全连接层替代掉卷积 -- RepMLP
- Translation of the paper "written mathematical expression recognition with bidirectionally trained transformer"
- Latex formula normal and italic
- (15) Flick custom source
猜你喜欢
ModuleNotFoundError: No module named ‘pytest‘
What if the notebook computer cannot run the CMD command
Nacos service registration in the interface
Installation and use of image data crawling tool Image Downloader
[learning notes] matlab self compiled Gaussian smoother +sobel operator derivation
[binocular vision] binocular stereo matching
Faster-ILOD、maskrcnn_ Benchmark installation process and problems encountered
【Mixup】《Mixup:Beyond Empirical Risk Minimization》
【Mixed Pooling】《Mixed Pooling for Convolutional Neural Networks》
Faster-ILOD、maskrcnn_ Benchmark trains its own VOC data set and problem summary
随机推荐
CPU register
What if the laptop task manager is gray and unavailable
Yolov3 trains its own data set (mmdetection)
ModuleNotFoundError: No module named ‘pytest‘
【Mixup】《Mixup:Beyond Empirical Risk Minimization》
浅谈深度学习中的对抗样本及其生成方法
Implementation of yolov5 single image detection based on onnxruntime
open3d学习笔记四【表面重建】
iOD及Detectron2搭建过程问题记录
【学习笔记】Matlab自编高斯平滑器+Sobel算子求导
【Programming】
超时停靠视频生成
【双目视觉】双目立体匹配
【多模态】CLIP模型
Label propagation
What if the laptop can't search the wireless network signal
【Random Erasing】《Random Erasing Data Augmentation》
How do vision transformer work?【论文解读】
【MagNet】《Progressive Semantic Segmentation》
win10+vs2017+denseflow编译