Spring-security Running Process

Source: Internet
Author: User
Tags anonymous auth http request

Spring-security Running Process

First, in Web. XML, the filter is configured as shown above, but this is actually not the class under the Spring-security package, but spring-web the following class, from the name can be seen, this class is a filter agent, according to my data, the reason is: spring-security Each of the filter chains must be injected with other beans from the Spring application context. However, the servlet specification does not make dependency injection on the servlet filter easy. Deletegatingfilterproxy solves this problem by acting as a "figurehead" in the spring application that is configured as the Bean's actual filter. The filter that really works is the filter Bean in the spring context. The agents in Web. XML invoke these beans in turn to protect the website resources. You can refer to one of my other blog posts: http://blog.csdn.net/u012156496/article/details/53485273

Through debugging discovery, a Filterchainproxy object is generated in the final Delegatingfilterproxy, and in this object, contains the security filter chain, the filter chain has three groups, the first group is for the login page, the second group is the logout page, The third group is the filtering of any request, and the control of the permissions is also implemented in this set of filter chains. My understanding is that mastering the role of the third group of filter chain, basic to Spring-security has a basic use of the master.

Here's a detailed look at the filter chain:

First filter: Securitycontextpersistencefilter
The main role is SecurityContext assembly, for the subsequent filter chain to use, if the user has logged in, re-access to other resources, according to SessionID in the session will be the previous saved SecurityContext removed, SecurityContext The user's login information is saved, the user is not required to log in again, only to verify that the user has permission to access the resource.
In the Dofilter method of the Securitycontextpersistencefilter:
SecurityContext contextbeforechainexecution = repo.loadcontext (holder);
The previous line of code is to remove SecurityContext, or null if the user has not yet been first accessed.

Second filter: Logoutfilter
This is the logout feature of spring-security, when we configure Auto-config to true on the Security:http node of the spring-security configuration file (as shown below), Then spring-security will automatically load the logout filter for us. After that, you can use Spring-security's logout function, and you can refer to spring security logout (example of spring Security), a foreign language I translated, which is an example of the use of the logout feature.

Third filter: Usernamepasswordauthenticationfilter
See the name, this filter is used to verify the user's login credentials, the filter can be implemented from the database to retrieve data to verify that the user login credentials are correct. In the course of my study, I found that it was only necessary to get a preliminary understanding of the implementation process of this filter. will be able to basically solve some of the requirements. What do you mean, that's what I found finally, in fact, this filter, is to take out form form in the user submitted login information, and we configure the user information in the configuration file, or through the database to remove the user information to match, the match succeeds, then pass. At first I learned very confused, is to complicate the problem, in fact, see the essence of the good. No nonsense, just say how to fetch user information from the database.

The above section of the springsecurity configuration file is very important, first of all about the data from the library to take the user login credentials.

Since it is from the database to fetch the user information, then take the data implementation code, it must be written by ourselves
Above is this implementation of the Org.springframework.security.core.userdetails.UserDetailsService interface implementation class, that is, by implementing this class, we based on the name of the logged-in user, the user information is removed, in the package to Springse Curity the user object that you want, return it to the springsecurity framework to use it. In the re-configuration file, we inject our implementation class through the Springsecurity configuration file. This enables the user's login information to be taken from the database.

Fourth filter: Basicauthenticationfilter
Org.springframework.security.web.authentication.www.BasicAuthenticationFilter, this filter is used when the Basic authentication method is turned on, and the Basic authentication method is a The user's authentication information is placed in the HTTP request header in the user authentication mode. If the request header does not start with basic, then this filter will not work

Fifth filter: Requestcacheawarefilter
Org.springframework.security.web.savedrequest.RequestCacheAwareFilter the use of this filter is officially explained as:
After the user has successfully logged on, re-restores the request because the logon was interrupted
There are several points to be explained in this explanation.
Interrupted request: The simple point is that there is a authenticationexception, accessdeniedexception two types of anomalies
Restore: Now that you can recover, the request message is saved to the cache.

Sixth filter: Securitycontextholderawarerequestfilter
Org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
From the class name can guess this filter is mainly packaging request object requests, see the source code

public void DoFilter (ServletRequest req, servletresponse Res, Filterchain chain) throws IOException, servletexception {
  chain.dofilter (New Securitycontextholderawarerequestwrapper ((httpservletrequest) req, rolePrefix), res);
}

The purpose of the Securitycontextholderawarerequestwrapper class for request wrapping is to implement some interface methods of the Servlet API IsUserInRole, Getremoteuser.
This filter looks very simple. The goal is simply to implement some interface methods for the servlet API in Java EE.
Some applications directly use the Getremoteuser method, the IsUserInRole method, which is actually implemented by this filter when using spring security.

Seventh Filter: Anonymousauthenticationfilter
The corresponding classpath is: Org.springframework.security.web.authentication.AnonymousAuthenticationFilter.
Anonymousauthenticationfilter filter is in Usernamepasswordauthenticationfilter, Basicauthenticationfilter, Remembermeauthenticationfilter these filters, so if none of the three filters are successfully authenticated, add an anonymously authenticated token to the current SecurityContext However, the getremoteuser of the servlet is not available to the login account. Because the Securitycontextholderawarerequestfilter filter is in front of Anonymousauthenticationfilter.

Omitted log section public void DoFilter (ServletRequest req, servletresponse Res, Filterchain chain) throws IOException, Servletexc
            eption {//applyanonymousforthisrequest always returns ture if (Applyanonymousforthisrequest ((httpservletrequest) req)) {
                If the current securitycontext does not have an authentication entity if (Securitycontextholder.getcontext (). getauthentication () = = null) { Generates an anonymous authentication entity and saves it to SecurityContext Securitycontextholder.getcontext (). Setauthentication (Create
            Authentication ((httpservletrequest) req));
    } else {}} chain.dofilter (req, res); } Protected authentication Createauthentication (HttpServletRequest request) {//Generate Anonymous authentication token, note the key here, userattr Ibute is injected by parsing the label Anonymousauthenticationtoken auth = new Anonymousauthenticationtoken (Key, Userattribute.getpasswor
        D (), userattribute.getauthorities ());

        Auth.setdetails (Authenticationdetailssource.builddetails (request));
   return auth; } 

The anonymous label is configured as.

<anonymous granted-authority= "role_anonymous" enabled= "true" username= "test"/>

Here the Username property is easily confused, username defaults to Anonymoususer, and is actually injected into the password variable of the Userattribute.
The Granted-authority property is injected into the Userattribute authorities authorization list.

Tenth filter: Myfiltersecurityinterceptor
This filter is customized to implement the permission control logic, which is injected into the spring-security filter chain via the spring-security configuration file. This filter needs to inherit Org.springframework.security.access.intercept.AbstractSecurityInterceptor.
The configuration file is as follows:

<security:http auto-config= "true" access-denied-page= "/403.jsp" > <security:form-login login-page= "/login . jsp "/> <!--Add a custom filter that implements the permission control logic to the spring-security filter chain--<security:custom-filter before=" FI Lter_security_interceptor "ref=" Myfilter "/> </security:http> <!--injection Myfiltersecurityinterceptor needed related b EAN--<bean id= "Myfilter" class= "Com.wr1ttenyu.security.MyFilterSecurityInterceptor" > <property Name= "AuthenticationManager" ref= "AuthenticationManager"/> <property name= "Accessdecisionmanager" ref= "myAc Cessdecisionmanagerbean "/> <property name=" Securitymetadatasource "ref=" Securitymetadatasource "/> & Lt;/bean> <!--to inject the bean into authenticationmanager with user information and <security:authentication-manager alias= "a
        Uthenticationmanager "> <security:authentication-provider user-service-ref=" Myuserdetailservice "> </security:authenticaTion-provider> </security:authentication-manager> <!--Custom get user Information implementation class--<bean id= "Myuserd Etailservice "class=" Com.wr1ttenyu.security.MyUserDetailService "/> <!--
    Here Myaccessdecisionmanagerbean is used to inject the Accessdecisionmanager attribute into the abstractsecurityinterceptor to implement the specific logic of the permission control-- <bean id= "Myaccessdecisionmanagerbean" class= "Com.wr1ttenyu.security.MyAccessDecisionManagerBean"/> <!-- Defines a filter bean that implements the permission control logic---<bean id= "Securitymetadatasource" class= " Com.wr1ttenyu.security.MyInvocationSecurityMetadataSource "/>

Once configured, the filter is added to the filter chain, which implements the code for authorization validation as follows:

public void Invoke (Filterinvocation fi) throws IOException, servletexception {
        // By calling the Beforeinvocation method of the parent class Abstractsecurityinterceptor,
        it is worth noting that in the logic of Beforeinvocation implementing permission control, If the requested resource path is not in Securitymetadatasource,
        //Then the resource does not have permission requirements by default, as long as the request passes.
        Interceptorstatustoken token = super.beforeinvocation (FI);
        try {
            fi.getchain (). DoFilter (Fi.getrequest (), Fi.getresponse ());
        } finally {
            super.afterinvocation ( token, null);
        }
    }

The above content mainly refer to: Http://www.codeweblog.com Station about spring-security Source analysis of the article
Not to be continued ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.