当前位置:网站首页>Five minutes to show you what JWT is
Five minutes to show you what JWT is
2022-04-23 20:07:00 【Handsome that handsome】
1. JSON Web Token What is it?
JSON Web Token (JWT) It's an open standard (RFC 7519), It defines a compact 、 The self-contained way , Used as a JSON Objects transmit information securely between parties . This information can be verified and trusted , Because it's digitally signed .
2. When should you use JSON Web Token
Use... In the following scenarios JSON Web Token It's very useful :
2.1: Authorization ( to grant authorization ) : This is the use of JWT The most common scenario . Once the user logs in , Each subsequent request will contain JWT, Allow users to access the routes allowed by the token 、 Services and resources . Single sign on is now widely used JWT A feature of , Because it costs very little , And it's easy to use across domains .
2.2: Information Exchange ( Information switching ) : For the safe transmission of information between parties ,JSON Web Tokens No doubt it's a good way . because JWT Can be signed , for example , Use public key / Private key pair , You can be sure that the sender is the person they are talking about . in addition , Because signatures are computed using headers and payloads , You can also verify that the content has not been tampered with .
3. JSON Web Token What is the structure of
JSON Web Token It's made up of three parts , They have dots between them (.) Connect . These are the three parts :
1. Header
2. Payload
3. Signature
therefore , A typical JWT It looks like this :
xxxxx.yyyyy.zzzzz
Next , Take a look at each part :
Header header It typically consists of two parts :token The type of (“JWT”) And algorithm name ( such as :HMAC SHA256 perhaps RSA wait ).
for example :
{
'alg': "HS256",
'typ': "JWT"
}
then , use Base64 For this JSON The code gets JWT The first part of
(1)Payload JWT The second part is payload, It contains declarations ( requirement ). Declarations are about entities ( Usually the user ) Claims and other data . There are three types of declarations : registered, public and private.
(2)Registered claims : There is a set of predefined declarations , They are not mandatory , But the recommended . such as :iss (issuer), exp (expiration time), sub (subject), aud (audience) etc. .
(3)Public claims : You can define it arbitrarily .
(4)Private claims : Used to share information between parties that agree to use them , It is not a registered or public declaration . Here is an example :
{
"sub": '1234567890',
"name": 'john',
"admin":true
}
Yes payload Conduct Base64 The code gets JWT Part two
Be careful , Not in JWT Of payload or header Put sensitive information in , Unless they're encrypted .
Signature
To get the signature part , You have to have it coded header、 Code of payload、 A secret key , The signature algorithm is header The one named in , Just sign them .
for example :
HMACSHA256(base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)
The signature is used to verify that the message has not changed during delivery , also , For those signed using the private key token, It can also be verified JWT Is the sender of .
Just look at a picture on the official website :
4. JSON Web Tokens How it works
At the time of certification , When users successfully log in with their credentials , One JSON Web Token Will be returned to . thereafter ,token User credentials , You must be very careful to prevent safety problems . generally speaking , You should not save the token longer than you need it .
Whenever a user wants to access a protected route or resource , The user agent ( Usually a browser ) You should bring it with you JWT, Typical , Usually placed in Authorization header in , use Bearer schema.
header It should look like this :
Authorization: Bearer
Protected routes on the server will be checked Authorization header Medium JWT Whether it works , If effective , Then users can access protected resources . If JWT Contain enough necessary data , Then you can reduce the need for database queries for certain operations , Though it may not always be .
If token It's in the authorization head (Authorization header) Sent in , So cross source resource sharing (CORS) It won't be a problem , Because it doesn't use cookie.
5. be based on Token Identity authentication And Server based authentication
5.1 Server based authentication
The discussion is based on Token How Authentication works and its benefits before , Let's take a look at what we did before :
HTTP Protocol is stateless , in other words , If we have authenticated a user , So the next time he asks , The server doesn't know who I am , We have to re certify
The traditional method is to store the authenticated user information on the server , such as Session. The next time the user requests, bring Session ID, The server then checks whether the user has been authenticated .
There are some problems with this server based authentication method :
Sessions : Every time a user is authenticated , The server needs to create a record to save user information , Usually in memory , As more and more users pass the authentication , The cost of the server here will be bigger and bigger .
Scalability : because Session It's in memory , This brings some scalability problems .
CORS : When we want to expand our applications , When our data is used by multiple mobile devices , We have to think about cross resource sharing . When using AJAX Call to get resources from another domain name , We may encounter the problem of forbidding requests .
CSRF : Users are vulnerable to CSRF attack .
5.2. JWT And Session The difference of The same thing is , They all store user information ; However ,Session It's on the server side , and JWT It's on the client side .
Session The biggest problem with storing user information is that it takes up a lot of server memory , Increase server overhead .
and JWT Method to disperse the user state to the client , It can obviously reduce the memory pressure of the server .
Session The state of is stored on the server side , The client only has session id; and Token The state of is stored on the client side .
5.3. be based on Token How Authentication works be based on Token Authentication is stateless , Server or Session No user information is stored in .
No session information means that the application can expand and add more machines as needed , You don't have to worry about where users log in .
Although this implementation may be different , But the main process is as follows :
- The user carries the user name and password to request access - The server verifies the user credentials - The app provides a token To the client - Client storage token, And carry it with you in every subsequent request - Server verification token And return the data
Be careful :
- Every request requires token -Token It should be placed in the request header in - We also need to set up the server to accept requests from all domains , use Access-Control-Allow-Origin: *
5.4. use Token The benefits of - Stateless and scalable :Tokens Store on client . Completely stateless , Scalable . Our load balancer can deliver users to any server , Because there is no state or session information anywhere . - Security :Token No Cookie.(The token, not a cookie.) Every time I ask Token Will be sent . and , Because there is no Cookie Be sent , It also helps to prevent CSRF attack . Even in your implementation token Stored to the client Cookie in , This Cookie It's just a storage mechanism , Instead of authentication mechanism . No session based information to manipulate , Because we don't have conversations !
And a little bit more ,token It will expire after a period of time , At this time, the user needs to log in again . It helps us stay safe . There's another concept called token revoke , It allows us to make specific token Even a group token Invalid .
5.5. JWT And OAuth The difference between -OAuth2 It's a kind of authorization framework ,JWT It's an authentication protocol - No matter which way you use, remember to use HTTPS To ensure data security -OAuth2 Used in the case of login with a third-party account ( For example, use weibo, qq, github Log in to a app), and JWT It's used to separate the front and back ends , It needs to be simple for the backstage API Use... For protection .
版权声明
本文为[Handsome that handsome]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210557450595.html
边栏推荐
- Software College of Shandong University Project Training - Innovation Training - network security shooting range experimental platform (8)
- R语言使用timeROC包计算存在竞争风险情况下的生存资料多时间AUC值、使用cox模型、并添加协变量、R语言使用timeROC包的plotAUCcurve函数可视化多时间生存资料的AUC曲线
- Building googlenet neural network based on pytorch for flower recognition
- nc基础用法3
- Devops integration - environment variables and building tools of Jenkins service
- Zero base to build profit taking away CPS platform official account
- NC basic usage 4
- [numerical prediction case] (3) LSTM time series electricity quantity prediction, with tensorflow complete code attached
- MFC获取本机IP(网络通讯时用得多)
- A brief explanation of golang's keyword "competence"
猜你喜欢
Zero base to build profit taking away CPS platform official account
Zero cost, zero foundation, build profitable film and television applet
MFCC: Mel频率倒谱系数计算感知频率和实际频率转换
【webrtc】Add x264 encoder for CEF/Chromium
指针数组与数组指针的区分
Deep learning -- Summary of Feature Engineering
SIGIR'22「微软」CTR估计:利用上下文信息促进特征表征学习
Grafana 分享带可变参数的链接
5 minutes to achieve wechat cloud applet payment function (including source code)
Openharmony open source developer growth plan, looking for new open source forces that change the world!
随机推荐
仓库管理数据库系统设计
Design of warehouse management database system
Leetcode XOR operation
Mfcc: Mel frequency cepstrum coefficient calculation of perceived frequency and actual frequency conversion
C6748 software simulation and hardware test - with detailed FFT hardware measurement time
R语言使用timeROC包计算无竞争风险情况下的生存资料多时间AUC值、使用confint函数计算无竞争风险情况下的生存资料多时间AUC指标的置信区间值
MySQL 进阶 锁 -- MySQL锁概述、MySQL锁的分类:全局锁(数据备份)、表级锁(表共享读锁、表独占写锁、元数据锁、意向锁)、行级锁(行锁、间隙锁、临键锁)
渤海期货这家公司怎么样。期货开户办理安全?
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(七)
[text classification cases] (4) RNN and LSTM film evaluation Tendency Classification, with tensorflow complete code attached
Is meituan, a profit-making company with zero foundation, hungry? Coupon CPS applet (with source code)
Introduction to electron tutorial 3 - process communication
山大网安靶场实验平台项目—个人记录(四)
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行1
Kibana reports an error server is not ready yet. Possible causes
aqs的学习
nc基础用法3
IIS data conversion problem: 16bit to 24bit
R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
音频编辑生成软件