当前位置:网站首页>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 :
 Insert picture description here
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 .
 Insert picture description here
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: *

 Insert picture description here
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

随机推荐