[In-depth explanation of Spring Security (1)] The overall structure of Spring Security

This blog is mainly about the notes I made while reading "Introduction to Spring Security" (I learned Spring Security before, but my understanding is relatively shallow, so I want to read this book a little deeper, all because of a bug last time tuned me for a few days)

The following is the online disk link of the pdf of this book, and I will share it with you (if it is expired, you can get it by private message).

Link: https://pan.baidu.com/s/1hFNX93PUtnd-qUaI1CsX8A?pwd=sh1w
Extraction code: sh1w

1. Overall structure

In the architectural design of Spring Security, Authentication and Authorization are separated. No matter what authentication method is used, it will not affect authorization. These are two independent existences. One of the benefits of this independence One, it is very convenient to integrate some external solutions. The figure below shows the core interfaces used for authentication and authorization (explained below):

insert image description here

Authentication

In layman's terms, authentication is identity authentication (who are you?)

AuthenticationManager

Authentication in Spring Security is AuthenticationManagerthe responsibility of the interface, which is defined as:

public interface AuthenticationManager {
    
    
    Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
  • Return Authenticationindicates that the authentication is successful;
  • An exception is returned AuthenticationException, indicating that the authentication failed.

The main implementation class of AuthenticationManager is ProviderManager, and many AuthenticationProvider instances are managed in ProviderManager. In a complete authentication process, Spring Security allows multiple AuthenticationProviders to implement multiple authentication methods, and these AuthenticationProviders are all ProviderManagermanaged by .

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-8AS17X0J-1685270725457) (C:\Users\myz03\AppData\Roaming\Typora\typora-user-images\ image-20230528110420464.png)]

Authentication

Authentication and authentication success information are mainly saved by the Authentication implementation class. The structure of the Authentication interface is as follows:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-mAzjFNq5-1685270725457) (C:\Users\myz03\AppData\Roaming\Typora\typora-user-images\ image-20230528110804016.png)]

  • getAuthorities: Get user authority information;
  • getCredentials: Get user credential information, generally refers to the password;
  • getDetails: Get user details;
  • getPrincipal: Get user identity information, user name, user object, etc.;
  • isAuthentiacted: Whether the user is authenticated successfully

Data preservation after login (SecurityContextHolder)

SecurityContextHolder is used to obtain user information after login. SpringSecurity will save the login user data in the Session. However, for ease of use, Spring Security has made some improvements on this basis, the most important of which is linear binding. When the user logs in successfully, SpringSecurity will save the successfully logged in user information to the SecurityContextHolder. Data storage in SecurityContextHolder is implemented by ThreadLocal by default. Variables created using ThreadLocal can only be accessed by the current thread, and cannot be accessed and modified by other threads, that is, user data is bound to the requesting thread.

When the login request is processed, Spring Security will take out the data in the SecurityContextHolder and save it in the session, and at the same time clear the data in the SecurityContextHolder. Whenever a request comes in the future, SpringSecurity will first take out the user login data from the Session and save it in the SecurityContextHolder for use in the subsequent processing of the request. At the same time, at the end of the request, the data in the SecurityContextHolder will be taken out and saved in Session, and then clear the data in the SecurityContextHolder of Security. This strategy is very convenient for users to obtain the currently logged-in user data in the Controller, Service layer, and any code.

In fact, it is for the convenience of us to get user information data, so as not to have to get it from the Session session every time. The bad thing is to judge the SessionID, and encapsulating it in the SecurityContextHolder reduces the judgment step. Just get it directly.

Authorization

In layman's terms, authorization is access control (what can you do?)

After the authentication is completed, the next step is authorization. In Spring Security's authorization system, there are two key interfaces:

  • AccessDecisionManager: Access Decision Manager, used to determine whether the access is allowed.

    • public interface AccessDecisionManager {
              
              
      
      	void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
      			throws AccessDeniedException, InsufficientAuthenticationException;
      
      	boolean supports(ConfigAttribute attribute);
      
      	boolean supports(Class<?> clazz);
      
      }
      
  • AccessDecisionVoter: Access to the decision voter, the voter will check whether the user has the due role, and then vote for, against or abstain. voter

    • public interface AccessDecisionVoter<S> {
              
              
      
      	int ACCESS_GRANTED = 1;// granted:赞同
      
      	int ACCESS_ABSTAIN = 0;// abstain:弃权
      
      	int ACCESS_DENIED = -1;// denied:反对,否认
      
      	boolean supports(ConfigAttribute attribute);
      
      	boolean supports(Class<?> clazz);
      
      	int vote(Authentication authentication, S object, Collection<ConfigAttribute> attributes);
      
      }
      

Both AccessDecisionVoter and AccessDecisionManager have many implementation classes. In AccessDecisionManager, AccessDecisionVoter will be traversed one by one to decide whether to allow users to access. Therefore, the relationship between AccessDecisionVoter and AccessDecisionManager is similar to the relationship between AuthenticationProvider and ProviderManager.

ConfigAttribute

In the vote method under the AccessDecisionVoter interface, the third parameter is a Collection collection object whose generic parameter is ConfigAttribute. You can understand it as a collection of character full name strings, and there is a getAttribute method inside.

public interface ConfigAttribute extends Serializable {
    
    
    
	String getAttribute();

}

In Spring Security, the role required by the user to request a resource (usually a network interface or a Java method) will be encapsulated into a ConfigAttribute object. There is only one getAttribute method in ConfigAttribute, which returns a String string, which is the role The name of the role has a ROLE_ prefix. What the voter AccessDecisionVoter does is to compare the relationship between the role of the user and the ConfigAttribute required to request a certain resource.

2. Summary

Understanding the overall architecture of Spring Security is mainly to prepare for the subsequent understanding of its internal principles. As a security framework, Spring Security mainly consists of two structures: authentication and authorization.

Authentication (Authentication) user information is stored indirectly in , and multiple authentication executors are managed in SecurityContextHolderAuthentication Management ( ), and they perform authentication, and the relevant details of authentication are encapsulated in .AuthenticationManagerAuthenticatoin

The authority name in Authorization can be obtained through the method, by ConfigAttributejudging whether the access is allowed, and the judgment is based on the result of the voting method.getAttributeAccessDecisionManagerAccessDecisionVotervote

Guess you like

Origin blog.csdn.net/qq_63691275/article/details/130915858