Author: Qu Ding


Blog:
mrdear.cn/

The previous article looked at how Spring Security intercepts requests and redirects them to the Filter chain. This article focuses on the role of nodes in these Filter chains.

The following is an analysis of the previous configuration, which is also performed in this article.


<security:http >
        <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
        <security:form-login/>
        <security:http-basic/>
        <security:logout/>
</security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="123456" authorities="ROLE_USER"/>
                <security:user name="admin" password="123456" authorities="ROLE_USER, ROLE_ADMIN"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
Copy the code

1. Origin of Filter chain

Each security: HTTP tag corresponds to a class of the SecurityFilterChain, that is, a Filter chain. The URL can be specified by its HTTP attribute. Otherwise, all urls in the scope are specified as follows: Security: HTTP Generates a Filter chain for all requests under /login.


    <security:http pattern="/login/**">
        ******
    </security:http>
Copy the code

The Filter chain can be clearly seen by clicking a breakpoint




2.SecurityContextPersistenceFilter

The class before all of the Filter, remove the user authentication information from SecurityContextRepository, the default implementation class for HttpSessionSecurityContextRepository, it will be removed from the Session has been authenticated user information, efficient To avoid querying user authentication information every time a request is made.

Once it is retrieved, it is placed into the SecurityContextHolder for use by other filters. The SecurityContextHolder uses ThreadLocal to store user authentication information, ensuring information isolation between threads, and finally clears the information.

You can configure the HTTP security-context-repository-ref attribute to control how you retrieve authenticated user information. For example, you can use Redis to store sessions. If sessions are not applicable, configure NullSecurityContextRe Pository, to avoid hogging server memory.

3.WebAsyncManagerIntegrationFilter

Provides integration with the securityContext and WebAsyncManager, which sets the securityContext to an asynchronous thread so that it can also get user context authentication information.

4.HeaderWriterFilter

It adds information to the Header of the request, controlled by using Security: HEADERS inside the HTTP tag.

5.CsrfFilter

Csrf, cross-site request forgery, does not have A deep understanding, but only knows that website B uses the trusted Cookie of website A to initiate A request, so as to complete authentication and forge A legitimate request.

The authentication method is to compare the token sent by the client with the token stored by the server to determine whether the request is forged. If you are interested, you can check the source code for further research.

6.LogoutFilter

If the URL is matched, the default value is /logout. After the URL is successfully matched, the user exits and the authentication information is cleared. This filter can disable if it has its own exit logic

7.UsernamePasswordAuthenticationFilter

Login Authentication filter, the default is to Authentication/login POST request, first of all, this method will be called attemptAuthentication try certification to obtain a certification Authentication object, and through sessionStrategy onAuthentica The tion performs persistence, which is to save authentication information, move to the next Filter, and finally call successfulAuthentication to perform the post-authentication event.

attemptAuthentication

This method is the main authentication method. Authentication is performed by entrusting the authentication-manager->authentication-provider configuration.

Such as for the Demo configuration for the following, the default manager of ProviderManager, use the provider for DaoAuthenticationProvider, userDetailService InMemoryUserDetail The sManager simply fetches user authentication information from memory, which is the user and admin information in the XML configuration below.


    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="123456" authorities="ROLE_USER"/>
                <security:user name="admin" password="123456" authorities="ROLE_USER, ROLE_ADMIN"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
Copy the code

Basic process for UserDeatilService certification according to the user name to authenticate the user’s information, and then through UserDetailsChecker. Check the user is state calibration, finally to the user through additionalAuthenticationChecks methods After the code verification is successful, the authentication is complete. Returns an authentication object.

Both are interface oriented, so users can easily extend their own authentication methods.

8.DefaultLoginPageGeneratingFilter

When the request isa login request, a simple login page is generated and returned, which can also be disabled with its own login logic

9.BasicAuthenticationFilter

Support for Http Basci authentication, which transmits the user name and password in the header encoded in Base64, as shown below. After successful authentication, the user information is put into the SecurityContextHolder.


 * Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Copy the code

10.RequestCacheAwareFilter

Resuming interrupted requests, not specifically explored

11.SecurityContextHolderAwareRequestFilter

Some wrappers for different versions of the Servlet API

12.AnonymousAuthenticationFilter

When the authentication information in the SecurityContextHolder is empty, an anonymous user is created and stored in the SecurityContextHolder

13.SessionManagementFilter

As in login authentication interception, persistent user login information can be stored in session, cookie or REDis.

14.ExceptionTranslationFilter

Exception interception, which is at the back of the Filter chain, can only intercept the nodes behind it and focus on AuthenticationException and AccessDeniedException. You can define an entryPoint here that returns 403 for an error request.

15.FilterSecurityInterceptor

The main authorization validation is called from the beforeInvocation method


Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
                .getAttributes(object);
Copy the code

HasRole (‘ROLE_USER’) is obtained, and 403 is returned based on the user information stored in SecurityContextHolder. For details, see HttpConf IgurationBuilder. CreateFilterSecurityInterceptor () method, to analyze its creating process which the load of the data, or analysis SecurityExpressionOperations subclasses, and its implementation method is authority appraisal.

conclusion

The whole authentication and authorization process is shown in the figure below, which is stolen online

Because it is study respect, what use is not very much, if have error please point out, in case mislead a person’s children.

In short, as a user you need to care about

  1. Logon authentications UsernamePasswordAuthenticationFilter
  2. Access authentication BasicAuthenticationFilter
  3. Authentication FilterSecurityInterceptor

The next article will look at implementing JWT validation using these three validations.

More details on these filters can be found in the blog: Blogosphere – Introduction to Spring Security