FastAPI from entry to actual combat (8) - understand Cookie, Session, Token and JWT in one article

You should be able to see from the title that this article is about front-end authentication. Authentication is identity authentication, which refers to verifying whether a user has access to the system. As long as it is web development, it is impossible not to learn this part of the content. Yes, many interviews will also ask, so this article will record several common ways in detail on this topic.

HTTP status

HTTP is stateless. That is to say, the state cannot be maintained between the HTTP requester and the responder, and they are all one-time. It does not know what happened to the previous and subsequent requests. But in some scenarios, we need to maintain state. Most typically, when a user logs in to Weibo, posting, following, and commenting should all be in the logged-in user state. In this case, various authentications come into being.

Before that, I also understand a little basic concept:

  • certified

Authentication is to verify the identity of the current user, such as user name and password login authentication, email sending login link, mobile phone number verification code authentication. Verify that the current user is himself, not a machine.

  • authorized

The user grants the third-party application the permission to access certain resources of the user, and the client grants some permission to the server-side application. The most common thing is that when the mobile application is installed, the APP asks the user whether to grant media access permission.

  • certificate

To achieve authentication and authorization, something is needed to identify the identity of the visitor. This identification is a credential. For example, if you go to the lobby of a bank, you don’t need authentication if you don’t need to do business, and you don’t need a credential. Just go shopping; but If you want to do business, you need to provide your identity certificate and bank card information. The ID card and bank card correspond to the voucher. With the voucher, you can authenticate and do business at the bank.

Cookie

Reference link: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies

Cookie is some data sent by the server to the user's browser and saved locally. The browser will store the cookie. When it sends a request to the browser next time, it will also send the cookie to the server, so that the server can know Are these two requests coming from the same browser?

cookie222

Cookies are mainly used in the following three aspects:

  • Session state management :

For example, the most common user login status, the client sends a request when logging in, the server performs verification after receiving the request, and sends a request success and setcookie response after the verification is successful, and the client completes the login after receiving the response. storage, the next time the page is refreshed, redirected, etc., the cookie will be sent to the server. The server receives the cookie and performs verification. If the verification is successful, it will directly send a response. If the verification fails, it will jump to the login page and log in again.

  • Personalization settings :

​For example, user-defined settings and theme settings, the same reason as above, setting and verification can guarantee the user-defined settings within the validity period.

  • Browser Behavior Tracking :

​ Since HTTP is stateless, the server cannot determine whether the sender of the current request is the same person. The server and the browser have a conversation, and the server can know the browser's behavior and can further track it.

Cookie application

See the next section for the content of this part, which is displayed and explained directly in the form of code.

Session

When the client sends a request, the server will create a memory space for this request. This object is the session object. When the session is created, a sessionid will be generated, and a cookie Set-Cookie:JSESSIONID=XXXXXXXsetting will be sent through the command. After receiving the response, the client will browse The server sets a cookie information, and when the cookie ends, the session ends.

Next, for all requests from the client 请求头都会带上携带有sessionid的cookie信息, the server returns the sessionid by reading the cookie information in the request header, further verifying the session, and continuing the session.

  • Disadvantages of sessions

​ The session is stored on the server. If it is a distributed architecture, it is likely to face the problem of invalidation.

Session application

It should be involved in the actual combat project later, so the experiment will not be carried out here.

The difference between Cookie and Session

  • Security :

​ Session is safer than Cookie, Session is stored on the server side, and Cookie is stored on the client side.

  • The types of access values ​​are different :

​ Cookie only supports storing string data. If you want to set other types of data, you need to convert it into a string. Session can store any data type.

  • The validity period is different :

​ Cookies can be set to persist for a long time. For example, the default login function we often use, Session generally has a short expiration time, and the client will be closed (by default) or Session will expire when it times out.

  • Storage sizes vary :

​ The data saved by a single cookie cannot exceed 4K, and the session can store much more data than cookies, but when there are too many visits, it will take up too many server resources.

Token

Token 的中文意思是"令牌"。主要用来身份验证。Compared with traditional authentication methods, Token has the characteristics of strong scalability and high security, and is very suitable for use in web applications or mobile applications. It is a string generated by the server that can be used as a credential for the client.

Session settings are more appropriate for small and medium-sized projects, but once the traffic increases, the server will save too much data, which will consume a huge amount of server.

In response to this problem, I wonder if it is possible not to save it in the server, but to the client to save it. For example, when the user logs in to the system, the server sends a token to the client, which contains the user's id. When the next request is made, this The token is brought back again, but there is still a problem with this. This is easy to forge, so it needs to be encrypted so that others cannot forge it.

The server does not save this token. When the user sends me the token, I will use the same algorithm and key to calculate a signature on the data and compare it with the signature in the token. If they are the same, my server will know The user has already logged in, and the user's id can be obtained directly. If it is not the same, the data must have been tampered with, and the server will return an error of verification failure.

  • The difference from cookies

When I saw this at the beginning, I was already confused. The generated data is sent to the client, and the client will send it to the server every time it requests. What is the difference between this and a cookie?

But if you think about it carefully, you will know that it is very different. A cookie is a data block that can store a lot of key-value pair data. A token is a token that only stores the data needed for verification . The token can be placed in the url, header, request body, or cookie, which is essentially a piece of data.

  • Summarize the verification process
  1. Client requests login with username and password
  2. The server receives the request and verifies the username and password
  3. After the verification is successful, the server will issue a token and return the token to the client
  4. After receiving the token, the client can store it, such as putting it in a cookie
  5. Each time the client requests resources from the server, it needs to carry the token issued by the server, which can be carried in the cookie or header
  6. The server receives the request, and then verifies the token contained in the client request. If the verification is successful, it returns the request data to the client.

Token vs. Session

Session and token are not contradictory, session is a storage mechanism, the purpose is to store login information; token is to provide authentication and authorization, encrypted data is user information, and the server needs to compare it with the database for user authentication.

  • Support cross-domain access :

Cookies cannot cross domains, and tokens do not use cookies (the premise is to put tokens in the request header), so there will be no information loss problem after crossing domains

  • stateless :

​ The token mechanism does not need to store session information on the server side, because the token itself contains the information of all logged-in users, so it can reduce the pressure on the server side

  • More suitable for CDN :

​ Can request all the data of the server through the content distribution network

  • More suitable for mobile terminals :

​ When the client is a non-browser platform, cookies are not supported, and the token authentication method will be much simpler

  • No need to worry about CSRF :

​ Since cookies are no longer relied on, CSRF will not occur when using token authentication, so there is no need to consider CSRF defense

JWT

JWT is an implementation of token, its full name is JSON Web Token. Official website: https://jwt.io/

JWT将用户信息保存在一个Json字符串中, and then encode to get a JWT token, and the JWT has signature information, which can be verified after receiving, so it can be used to securely transmit information as a Json object between parties.

  • JWT authentication process:
  1. The front end will用户信息通过表单发送到后端
  2. The backend gets the information and compares it with the database. After the verification is successful, it will contain it 用户信息的数据作为JWT的主要载荷, and then encode it with the JWT Header and sign it to get a JWT Token
  3. The backend will JWT Token字符串作为登录成功的结果返回给前端. The front end can store the returned results and delete them when exiting the browser
  4. When the front end sends a request 把JWT Token放置到HTTP请求头中的Authorization属性中(to solve the problems of XSS and XSRF)
  5. rear end检查前端传过来的JWT Token后进行验证
  6. After the verification is passed, the backend parses the information contained in the JWT Token for further processing

JWT structure

JWT consists of 3 parts: 标头(Header)、有效载荷(Payload)和签名(Signature). During transmission, the three parts of the JWT will be Base64-encoded and then .connected to form the final transmitted string:

Base64(Header).Base64(Payload).HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)

Header

JWT头It is a JSON object describing the JWT metadata. The alg attribute indicates the algorithm used for the signature. The default is HMAC SHA256 (written as HS256); the typ attribute indicates the type of the token, and the JWT token is uniformly written as JWT. Finally, use the Base64 URL algorithm to convert the above JSON object into a string and save it:

{
    
    
  "alg": "HS256",
  "typ": "JWT"
}

Payload

有效载荷The part is the main content part of the JWT, and it is also a JSON object that contains the data that needs to be passed. JWT specifies seven default fields to choose from:

iss:发行人
exp:到期时间
sub:主题
aud:用户
nbf:在此之前不可用
iat:发布时间
jti:JWT ID用于标识该JWT

In addition to the above default fields, we can also customize private fields, and generally put data containing user information into the payload:

{
    
    
  "sub": "1234567890",
  "name": "MinChess",
  "admin": true
}

Signature

签名哈希The part is to sign the above two parts of the data, and the data needs to be used to base64编码后的header和payloadgenerate a hash through the specified algorithm to ensure that the data will not be tampered with. First, you need to specify a key (secret). This password is only stored on the server and cannot be disclosed to the user. Then, use the signature algorithm specified in the header (HMAC SHA256 by default) to generate a signature according to the following formula

HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)

After calculating the signature hash, the three parts of the JWT header, payload and signature hash are combined into a string, and each part is separated by . to form the entire JWT object

Types of JWTs

JWT(JSON Web Token)Refers to a specification that allows the use of JWT to transfer safe and reliable information between two organizations. The specific implementation of JWT can be divided into the following categories:

  • nonsecure JWT: unsigned, insecure JWT

    There is no signature algorithm specified in the header, only algsum typand no signature.

  • JWS: signed JWT

    JWS specifies the algorithm in the header, and finally has the token corresponding to the signature.

  • JWE: The encrypted JWT of the payload part

    JWE is the JWT encrypted by the payload data, so that the plaintext data of the payload cannot be directly parsed

JWTSummary

JWT就是Token的一种规范,三个部分,头+载荷+签名,头中声明类型、加密算法等,载荷装载主要数据,签名由算法+头+载荷+密钥组成,token也是三个部分,前面两个部分是明文的,前端可以直接进行解析获取到有效数据,所以不能放敏感数据;

When I didn’t understand it at the beginning, I still don’t know why encryption is needed. Encryption is also plain text. What is the meaning of encryption? Later, I figured it out later. Encryption only ensures that the data in the first two parts will not be modified. If modified, an error will be returned.

The verification process is that the server gets the data, decodes the header and payload , and further signs the decoded result combined with the key , and then compares the result with the signature returned by the client. If the comparison is different, an error is returned.

I personally feel that the records are relatively clear, and the specific actual combat will be further operated later.

When I didn’t understand it at the beginning, I still don’t know why encryption is needed. Encryption is also plain text. What is the meaning of encryption? Later, I figured it out later. Encryption only ensures that the data in the first two parts will not be modified. If modified, an error will be returned.

The verification process is that the server gets the data, decodes the header and payload , and further signs the decoded result combined with the key , and then compares the result with the signature returned by the client. If the comparison is different, an error is returned.

I personally feel that the records are relatively clear, and the specific actual combat will be further operated later.


Thanks for reading!
Blog address: FastAPI from entry to actual combat (8) - understand Cookie, Session, Token and JWT in one article

Welcome to follow the blogger's personal mini program!

Guess you like

Origin blog.csdn.net/qq_45730223/article/details/128088422