Open Source Tools Series 8: Spring Security

Spring Security is an authentication and authorization framework that supports authentication modes such as HTTP BASIC authentication header (based on IETF RFC-based standard), HTTP Digest authentication header (IETF RFC-based standard), Form-based authentication (for simple user interface), OpenID authentication, etc. Spring Security enables the current system to quickly integrate these authentication mechanisms or implement its own set of authentication mechanisms.

What is Spring Security

 

  • Spring Security is an authentication and authorization framework that supports authentication modes such as HTTP BASIC authentication header (based on IETF RFC-based standard), HTTP Digest authentication header (IETF RFC-based standard), Form-based authentication (for simple user interface), OpenID authentication, etc. Spring Security enables the current system to quickly integrate these authentication mechanisms or implement its own set of authentication mechanisms.
  • Spring Security is a powerful, highly customizable authentication and access control framework. It is the de facto standard for securing Spring-based applications.
  • Spring Security is a framework for Java applications. Like all Spring projects, the real power of Spring Security is that it can be easily extended to meet custom needs.

authority management

Authentication and Authorization

In Spring Security, authority management mainly includes two aspects: authentication and authorization. In simple terms, authentication is the login authentication of the user; authorization is the amount of resources the user can access after successful login.

What is Authentication and Authorization

authority management

Basically, systems involving user participation must perform authority management. Authority management belongs to the category of system security. Authority management realizes the control of user access to the system, and controls users to access and only access authorized resources according to security rules or security policies. Rights management includes two parts: user identity authentication and authorization, referred to as authentication and authorization. For resource users that need access control, they must first go through identity authentication, and only after the authentication is passed, the user has access rights to the resource can access it.

certified

Authentication is the process of judging whether a user is a legitimate user. The most commonly used simple identity authentication method is that the system checks the user name and password (password) entered by the user to see if it is consistent with the user name and password stored in the system to determine whether the user's identity is correct. This is like the account number and password we need to log in to QQ, WeChat, game account, etc.~

authorized

Authorization, or access control, controls who can access which resources. After identity authentication, the subject needs to be assigned permissions to access system resources, and some resources cannot be accessed without permissions. This is like a school's website, which has resources that students can access, but teachers' resources cannot be accessed by students~

Overall structure

architecture design

In the architectural design of Spring Security, authentication and authorization are separated, but no matter what authentication method is used. Neither will affect the authorization. These are two independent existences. One of the benefits of this independence is that it is very convenient to integrate some external solutions.

1. Certification

// AuthenticationManager 接口,在Spring Security中认证是由 AuthenticationManager 来负责的,接口定义为:
public interface AuthenticationManager {
    Authentication authenticate(Authentication var1)
        throws AuthenticationException;
}
// Authentication接口,认证以及认证成功的信息主要是由 Authentication 的实现类进行保存的,接口定义如下:
public interface Authentication extends Principal, Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    Object getCredentials();
    Object getDetails();
    Object getPrincipal();
    boolean isAuthenticated();
    void setAuthenticated(boolean var1) throws IllegalArgumentException;
}

Method introduction:

  • getAuthorities Get user authority information
  • getCredentials Obtain user credential information, generally refers to password
  • getDetails Get user details
  • getPrincipal Get user identity information, user name, user object, etc.
  • isAuthenticated Whether the user is authenticated successfully
// SecurityContextHolder 类,SecurityContextHolder 用来获取登录之后用户信息。定义如下(省略了一些属性和方法):
public class SecurityContextHolder {
    public static void clearContext() {
        strategy.clearContext();
    }
    public static SecurityContext getContext() {
        return strategy.getContext();
    }
    public static int getInitializeCount() {
        return initializeCount;
    }
    public static void setContext(SecurityContext context) {
        strategy.setContext(context);
    }
    public static void setStrategyName(String strategyName) {
        strategyName = strategyName;
        initialize();
    }
    public static SecurityContextHolderStrategy getContextHolderStrategy() {
        return strategy;
    }
    public static SecurityContext createEmptyContext() {
        return strategy.createEmptyContext();
    }
    public String toString() {
        return "SecurityContextHolder[strategy='" + strategyName + "'; initializeCount=" + initializeCount + "]";
    }
}

  • Spring Security will save the logged-in 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 thread binding.
  • When the user logs in successfully, Spring Security will save the successfully logged in user information into 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 and the requesting thread are bound together.
  • When the login request is processed, Spring Security will save the data in the SecurityContextHolder to the Session, and clear the data in the SecurityContextHolder at the same time. Whenever a request comes in the future, Spring Security 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.
  • This strategy is very convenient for users to obtain the currently logged-in user data in the Controller, Service layer, and any code.

Notice

Note: When Authentication is returned, it means that the authentication is successful; when an AuthenticationException is returned, it means that the authentication has 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

AuthenticationProvider is used to implement multiple authentication methods, and these AuthenticationProviders are all managed by ProviderManager.

2. Authorization

In Spring Security's authorization system, there are two key interfaces: AccessDecisionManager and AccessDecisionVoter.

// AccessDecisionManager (访问决策管理器),用来决定此次访问是否被允许。接口定义如下:
public interface AccessDecisionManager {
    void decide(Authentication var1, Object var2, Collection<ConfigAttribute> var3) throws AccessDeniedException, InsufficientAuthenticationException;
    boolean supports(ConfigAttribute var1);
    boolean supports(Class<?> var1);
}
// AccessDecisionVoter (访问决定投票器),投票器会检查⽤户是否具备应有的角色,进而投出赞成、反对或者弃权票。接口定义如下:
public interface AccessDecisionVoter<S> {
    int ACCESS_GRANTED = 1;
    int ACCESS_ABSTAIN = 0;
    int ACCESS_DENIED = -1;
    boolean supports(ConfigAttribute var1);
    boolean supports(Class<?> var1);
    int vote(Authentication var1, S var2, Collection<ConfigAttribute> var3);
}

Notice

Note: It should be noted that AccessDecisionManager will traverse AccessDecisionVoter one by one to decide whether to allow users to access.

// ConfigAttribute,用来保存授权时的角色信息。接口定义如下:
public interface ConfigAttribute extends Serializable {
    String getAttribute();
}

In Spring Security, the role required by the user to request a resource will be encapsulated into a ConfigAttribute object.

There is only one getAttribute method in ConfigAttribute, which returns a String string, which is the name of the role.

Generally speaking, role names have a ROLE_ prefix. What the voter AccessDecisionVoter does is to compare the relationship between the roles of the user and the ConfigAtuibute required to request a certain resource.

project use

Spring Security

In fact, Spring Security has been born for many years before Spring Boot appeared.

However, the development of Spring Security has not been very smooth. The main problem is that the process of integrating and configuring the Spring Security framework in the application is relatively complicated.

But with the rise of Spring Boot, based on the automatic configuration solution for Spring Security provided by Spring Boot, developers can use Spring Security with zero configuration.

If you want to use Spring Security in your Spring Boot application, you only need to add the following dependencies to the pom file of the Maven project:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
</dependency>

summary

In short, the Spring Security framework, based on daily development, has a functional system that fully meets various security requirements.

Different functions correspond to different application scenarios. Various functions provided by the Spring Security framework can be used to ensure the security of the system in ordinary single applications, micro-service architectures, and responsive systems.

project information

Github project address:

https://github.com/spring-projects/spring-security

Spring Security official documentation: https://spring.io/projects/spring-security

About HummerRisk

HummerRisk is an open source cloud-native security platform that solves cloud-native security and governance issues in a non-intrusive manner. Its core capabilities include hybrid cloud security governance and K8S container cloud security detection.

 

Guess you like

Origin blog.csdn.net/wolaisongfendi/article/details/131396235