[User Authentication] Password encryption, user state storage, cookie, session, token

Related concepts

Authentication and Authorization

Authentication is the process of verifying who you are while authorization is the process of verifying that you have access

The logic of user authentication

  1. Get the username and password submitted by the user
  2. According to the user name, query the database to obtain complete user information, including the real password
  3. Compare the submitted password with the queried password
  4. If the two are equal, the user authentication is successful; otherwise, the user authentication fails

password encryption

encryption and decryption

encryption

The basic process of data encryption is to  process  the  original  plaintext  file or data according to  a certain algorithm to make it an unreadable  piece of code, usually called  "ciphertext" . In this way,  the purpose of protecting data  from being  stolen and read by illegal persons is achieved .

decrypt

The reverse process  of  encryption  is  decryption , which is  the process of  converting  the encoded information into its original data  .

Encryption Algorithm

The encryption algorithm is divided  into symmetric encryption  and  asymmetric encryption . The encryption key of the symmetric encryption algorithm  is the same as the decryption key , and the encryption key of the asymmetric encryption algorithm  is different from the decryption key . In addition, there is a type of   hash  algorithm that does not require a key .

Common  symmetric encryption  algorithms mainly include  DES, 3DES, AES etc.
Common  asymmetric algorithms  mainly include  RSA, DSA etc.
Hash algorithms  mainly include  SHA-1, MD5 etc.

Symmetric encryption

Symmetric encryption algorithm  is an earlier encryption algorithm, also known as  shared key encryption algorithm . In  the symmetric encryption algorithm  , only one key is used, and both the sending  and  receiving  parties use this key to  encrypt  and  decrypt data . This requires both the encryption and decryption parties to know the encryption key in advance.

Common algorithms:

image.png

  1. Data encryption process: In the symmetric encryption algorithm, the data sender  puts  the plaintext  (original data) and  the encryption key  through special  encryption processing to generate complex  encrypted ciphertext  for transmission.
  2. Data decryption process: After the data receiver  receives the ciphertext, if he wants to read the original data, he needs to use  the key used for encryption  and  the inverse algorithm of the same algorithm  to decrypt the encrypted ciphertext to restore it to  readable plaintext .

asymmetric encryption

Asymmetric encryption algorithm , also known as  public key encryption algorithm . It requires two keys, one is called  the public key  ( public key), which is  the public key , and the other is called  the private key  ( private key), which is  the private key .

Common algorithm: RSA

Because  encryption  and  decryption  use two different keys, this algorithm is called an  asymmetric encryption algorithm .
image.png

  1. If   data  is encrypted with a public key , it  can  only be decrypted with the corresponding  private key .
  2. If   data  is encrypted with a private key ,  it can  only be decrypted with the corresponding  public key .

Example : Party A generates  a pair of keys  and discloses one of them as  a public key  to others.  Party B who obtains the public key encrypts  the confidential information with this key   and then sends it to Party A. Party A then uses its own Another dedicated key  ( private keyis stored  to decrypt the encrypted  information  .

Comparison:
(1) Symmetric encryption uses the same key for encryption and decryption, so the speed is fast, but the security is not high because the key needs to be transmitted over the network.

(2) Asymmetric encryption uses a pair of keys, public key and private key, so the security is high, but the encryption and decryption speed is slow.

(3) The solution is to encrypt the symmetric encryption key with the asymmetric encryption public key, and then send it out, and the receiver uses the private key to decrypt to obtain the symmetric encryption key, and then the two parties can use symmetric encryption to communicate .

hash algorithm

A class of  hashing algorithms that do not require a  key  .

Common algorithms: md5,

With salt

Generally, passwords are not directly stored in plain text.
They will be encrypted and stored by using certain algorithms, such as md5,
but there is a possibility of brute force cracking.
Solution: final password = other + salt value + md5 (plain text password + salt value)
greatly improves security
Salt value: a random string

protocol

OAuth2

image.png

Save user login state

HTTP is a stateless protocol that does not save state.

cookie

  • save the state on the client side
    Pasted image 20220612224250.png
  1. The client accesses the login interface of the server
  2. The server authenticates the user according to the requested username and password, and writes the cookie to the response after successful authentication
//创建cookie  
Cookie cookie = new Cookie("islegal","yes");  
//设置cookie的访问路径(哪些请求路径可以访问cookie),默认所有都可以访问  
cookie.setPath("/project1/checkServlet");  
//设置生命周期,取值有三种:
 //大于0,单位是秒;
 //等于0,浏览器关闭
 //小于0,-1 (默认)内存释放  
cookie.setMaxAge(60*60);  
resp.addCookie(cookie);

Pasted image 20220613142653.png
3. The client receives the response and saves it
image.png

  1. When the user requests again, the cookie will be carried
    image.png
  2. If the server can access the cookie, it can retrieve data from it
Cookie[] cookies = req.getCookies();  
if(cookies!=null){
    
      
    for (Cookie cookie : cookies) {
    
      
        System.out.println(cookie.getName()+" "+cookie.getValue());  
    }  
}

tip:
How to modify the cookie?
Create a new cookie, as long as the path is consistent with the name of the cookie, you can modify the cookie value

Advantages and disadvantages

Pasted image 20220613140452.png

session

Server-based state preservation

  • The server will allocate a Session object for each session
  • Multiple requests initiated by the same browser belong to one session (Session)

process:

  1. When the Session is used for the first time, the server will automatically create the Session and JSeeisonID, and create a Cookie to store the JSessionId and send it back to the client.
    Pasted image 20220613142745.png
  2. The next time the unified browser accesses the server again, it will carry the JSessionId through the cookie to obtain the original Session
  • scope
    • One session (possibly multiple requests, browser closed, session ended) is valid
    • Sessions between different components can be shared, and there is a dedicated memory in java to save sessions

Passivation: means that after closing the server, the data stored in the session will be serialized and stored on the disk without
closing the browser. Activation: means that the data in the session has been passivated. The data on the disk is read into the session

  • session life cycle
    Pasted image 20220613144830.png
//通过req获得session ,
//有一个boolean参数,默认true,没有则会创建一个新的会话;false如果没有回话,则不会创建
HttpSession session = request.getSession();  
System.out.println(session.getId());  
//保存数据  
session.setAttribute("name","gao");  
//获取数据  
String  name = (String)session.getAttribute("name");  
//移除数据  
session.removeAttribute("name");  
//设置sesison的最大有效时间,单位秒  
session.setMaxInactiveInterval(60*60);  
//手动销毁  
session.invalidate();

distributed

cookie

The previous solutions were all modified on the server side. The cookie solution is a client-side solution, which saves the session information in the cookie, that is, saves the user information in the cookie, so that the server does not need to save the session (user information). Every time a request is made, the cookie is passed to the server, so that the server knows which user it is.

This solution is relatively simple to implement, and does not occupy memory resources on the server side . But this program has a big problem.

1. Cookies are limited on the client side, and the storage capacity is also very small.
2. Security is very problematic, because they are stored locally and can be easily obtained by others.

session replication

Session replication is a server cluster session management mechanism that is widely used in small enterprise applications. It is not used in real development. Clusters are built by web servers (such as Tomcat).

Existing problems:

The principle of session synchronization is to asynchronously synchronize sessions by sending broadcasts in the same local area network. Once there are more servers and concurrently uploaded, the amount of data that needs to be synchronized by the session will be large, and all sessions on other servers need to be synchronized to this server. On the Internet, it will bring a certain amount of network overhead, and when the number of users is particularly large, there will be insufficient memory

advantage:

The session information between servers is synchronized. When any server is down, it will not affect the session status in other servers. The configuration is relatively simple.

Tomcat already supports the development and management mechanism of distributed architecture. You can modify the configuration of Tomcat to support session replication, and synchronize session objects among several servers in the cluster, so that each server saves the session information of all users, so that any The downtime of a local machine will not cause the loss of session data, and when the server uses the session, it only needs to be obtained on the local machine

session binding (paste)

We use nginx's reverse proxy and load balancing. Previously, the client would be assigned to one of the servers for processing. The specific server to be assigned for processing depends on the server's load balancing algorithm (round-robin, random, ip- hash, weight, etc.), but we can bind the client and the server based on the ip-hash strategy of nginx, and the same client can only access the server, no matter how many requests the client sends, it will be sent by the same server deal with

Disadvantages :

  • It is easy to cause a single point of failure. If a server goes down, the session information on that server will be lost
  • The front end cannot have load balancing, if there is, there will be problems with session binding

Advantages :

  • Simple configuration

redis:session centralized management

image.png

Advantages and disadvantages

Session advantages:
1. The information in the session is stored on the server side, which increases data security to a certain extent compared to cookies.
2. Session data is stored on the server side, which is more convenient to manage than jwt, that is to say, when users log in and log out actively, they only need to add and delete the corresponding session, which is very convenient to manage.

Disadvantages of session:
1. The session is stored on the server side, which increases the overhead of the server. When there are many users, the performance of the server will be greatly reduced.
3. Because user identification is based on cookies, if cookies are intercepted, users will be vulnerable to cross-site request forgery attacks.
4. After the user is authenticated, the server will record the authentication. If the authentication record is stored in the memory, it means that the user must request on this server next time, so that the authorized resource can be obtained. For distributed applications, the capacity of the load balancer is correspondingly limited. This also means that the scalability of the application is limited.

token

image.png

  1. Client requests server login
  2. After the server authenticates the user, when returning a response, a token is generated
    1. The common way to generate token is JWT
  3. The client receives the response and saves the token to localStorage or sessionStorage
  4. When the client accesses the server next time, it will carry the token through the Header

JWT

JSON Web Tokens

The Token of the JWT standard has three parts:

1. header (header), header information mainly includes (parameter type - JWT, signature algorithm - HS256)
2. poyload (load), load is basically the information you want to store (because the information will be exposed, it should not Add any sensitive data in the payload)
3.sign (signature), the function of the signature is to prevent malicious tampering of data

The middle is separated by a dot, and they all use Base64 encoding, so the real Token looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJuaW5naGFvLm5ldCIsImV4cCI6IjE0Mzg5NTU0NDUiLCJuYW1lIjoid2FuZ2hhbyIsImFkbWluIjp0cnVlfQ.SwyHTEx_RQppr97g4J5lKXtabJecpejuef8AqKYMAJc

Header

The Header part is mainly composed of two parts, one is the type of Token, and the other is the algorithm used. For example, the type below is JWT, and the algorithm used is HS256.

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

The above content needs to be encoded in the form of Base64, so it becomes like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload

The Payload contains the specific content of the Token, some of which are standard fields, and you can also add other required content. The following are the standard fields:

iss:Issuer,发行者
sub:Subject,主题
aud:Audience,观众
exp:Expiration time,过期时间
nbf:Not before
iat:Issued at,发行时间
jti:JWT ID

For example, the following Payload uses iss issuer, exp expiration time, and two custom fields, one is name and the other is admin.

{
    
    
    "iss" : "csdn.net",
    "exp" : "201511205211314",
    "name" : "维C果糖",
    "admin" : true
}

After encoding with Base64, it becomes like this:

eyJpc3MiOiJuaW5naGFvLm5ldCIsImV4cCI6IjE0Mzg5NTU0NDUiLCJuYW1lIjoid2FuZ2hhbyIsImFkbWluIjp0cnVlfQ

Signature

The last part of JWT is Signature, which has three parts. First, the header and payload encoded with Base64, and then encrypted with an encryption algorithm. When encrypting, a Secret should be put in, which is equivalent to a key. This key is secret stored on the server side.

header
payload
secret
var encodedString = base64UrlEncode(header) + "." + base64UrlEncode(payload); 
HMACSHA256(encodedString, 'secret');

After processing it looks like this:

SwyHTEx_RQppr97g4J5lKXtabJecpejuef8AqKYMAJc

The final Token generated on the server and sent to the client looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJuaW5naGFvLm5ldCIsImV4cCI6IjE0Mzg5NTU0NDUiLCJuYW1lIjoid2FuZ2hhbyIsImFkbWluIjp0cnVlfQ.SwyHTEx_RQppr97g4J5lKXtabJecpejuef8AqKYMAJc

After the client receives the Token, it will be stored, and it will take the Token with it when it sends a request to the server next time. The server receives the Token, then verifies it, and returns the desired resource to the client after passing.

How does the server verify?
It is the same as the way to generate the signature, and then compare whether the signature is the same

Advantages and disadvantages

  • There is no need to save session information on the server side, especially for distributed microservices.
  • Self-contained (Self-contained): The payload contains all the information needed by the user, avoiding multiple queries to the database
  • Compact: It can be sent through URL, POST parameters or HTTP header, because the data volume is small and the transmission speed is fast
  • Because the Token is stored on the client in the form of JSON encryption, JWT is cross-language, and in principle any web form supports it.

Security Question

CSRF

When a website uses cookies to save the user's login status, it may be induced by a malicious site to initiate a sensitive request to the target website without knowing it. csrf protection means that when a sensitive request is sent to the target website, it is required to carry csrf_token, which is a
customer The pseudo-random number attached to the end browser, the request sent by the malicious site will not carry this data.
springsecurity enables csrf protection by default. For put, post and other methods (excluding get), it is required to carry csrf_token when requesting, and the front and rear separation projects are originally used token, no need to enable csrf protection

frame

Spring Security

Shrio

References

Guess you like

Origin blog.csdn.net/weixin_50799082/article/details/131157233