Spring security source analysis of the two---Web package analysis

Source: Internet
Author: User
Tags cas http digest authentication session id

Spring is a very popular and successful Java application development framework. Spring security is based on the spring framework and provides a complete solution for WEB application security. In general, the security of a WEB application includes two parts of user authentication (authentication) and user authorization (Authorization). User authentication refers to verifying that a user is a legitimate principal in the system, which means that the user can access the system. User authentication generally requires the user to provide a user name and password. The system validates the user name and password to complete the authentication process. User authorization refers to verifying that a user has permission to perform an action. In a system, different users have different permissions. For example, for a file, some users can only read, and some users may make changes. In general, the system assigns different roles to different users, and each role corresponds to a series of permissions.

The Spring Security framework is well supported for the two scenarios mentioned above. In terms of user authentication, the Spring Security framework supports mainstream authentication methods, including HTTP Basic authentication, HTTP form validation, HTTP Digest authentication, OpenID, and LDAP. In terms of user authorization, Spring Security provides role-based access control and access control List,acl, which allows fine-grained control of the domain objects in the application.

This article first analyzes the security protections provided by spring-security from a Web package.

1. Access module:

Where Exceptiontranslationfilter: Handles all accessdeniedexception and Authenticationexception exceptions thrown by the filter chain.

Webinvocationprivilegeevaluator: Allows users to determine whether they have permission to access a specific Web URL.

1.1 Channel Packet: Ensure that Web requests are received from the specified transport channel.

which

Channelprocessingfilter: Ensure that a Web request passes through the required channel. Use filterinvocation internally to represent request requests, allowing you to use Filterinvoctionsecuritymetadatasource to query properties on the app.
The agent Channeldecisionmanager to handle the real channel security decision and the necessary action. If the response is submitted by Channeldecisionmanager, the channelprocessingfilter will not be processed.

The following example enforces access to both the login form and the access under the/secure path through HTTPS.

<BeanID= "Channelprocessingfilter"class= "Org.springframework.security.web.access.channel.ChannelProcessingFilter">  < Propertyname= "Channeldecisionmanager"ref= "Channeldecisionmanager"/>  < Propertyname= "Securitymetadatasource">    <Security:filter-security-metadata-sourcePath-type= "Regex">      <Security:intercept-urlpattern= "\a/secure/.*\z"Access= "Requires_secure_channel"/>      <Security:intercept-urlpattern= "\a/login.jsp.*\z"Access= "Requires_secure_channel"/>      <Security:intercept-urlpattern= "\a/.*\z"Access= "Any_channel"/>    </Security:filter-security-metadata-source>  </ Property></Bean><BeanID= "Channeldecisionmanager"class= "Org.springframework.security.web.access.channel.ChannelDecisionManagerImpl">  < Propertyname= "Channelprocessors">    <List>    <refBean= "Securechannelprocessor"/>    <refBean= "Insecurechannelprocessor"/>    </List>  </ Property></Bean><BeanID= "Securechannelprocessor"class= "Org.springframework.security.web.access.channel.SecureChannelProcessor"/><BeanID= "Insecurechannelprocessor"class= "Org.springframework.security.web.access.channel.InsecureChannelProcessor"/>
Channeldecisionmanager: Determines whether a web channel provides sufficient security.
Channelprocessor: Determines whether a web channel meets specific security conditions.
Channelentrypoint: Used by Channelprocessor to start a web channel.

1.2 Expression Pack:

Securityexpressionhandler is a façade that separates intrinsic expression object implementations from the requirements of spring security for secure expressions.

Defaultwebsecurityexpressionhandler is the default implementation of Securityexpressionhandler.

    protected securityexpressionoperations createsecurityexpressionroot (authentication authentication, FilterInvocation FI) {         New websecurityexpressionroot (authentication, FI);        Root.setpermissionevaluator (Getpermissionevaluator ());        Root.settrustresolver (trustresolver);        Root.setrolehierarchy (Getrolehierarchy ());         return root;    }

1.3 Intercept Package: Enhance the security of HTTP requests, especially URL requests.

In this filtersecurityinterceptor, the filter is implemented to increase the security of HTTP resources. This security interceptor requires filterinvocationsecuritymedatasource.

2. Authentication Module

Authentication processing mechanism, support a variety of protocols such as Basic,cas,form login, such as submit authentication information.

2.1 Logout and RememberMe bag

which

Logoutfilter logs the user's exit, which contains a set of Logouthandler. These hangler applications are sorted sequentially, in the order that you want to invoke Tockenbasedremembermeservices and Securitycontxtlogouthander. After exiting, it will be up to Logoutsucesshandler or Logoutsuccesurl to decide where to jump. Who determines the construction method that relies on creating logoutfilter.

Remembermeauthenticationfilter Check if there are authentication objects in the SecurityContext, And when a remembermeservices implements the request, a Remember-me authentication token is set to SecurityContext. This filter invokes the Autologin method implemented by Remembermeservices, and if the above method returns a non-empty authentication object, it is passed to AuthenticationManager, This will allow any particular authentication to be completed. If the authentication results are returned successfully, it will be set to SecurityContext.

If the certification is successful, a interactiveauthenticationsuccessevent time will be published to the application context, if the authentication is unsuccessful, there will be no event release, Because it is unsuccessful, it is recorded as an application event for a particular authenticationmanager. Under normal circumstances, whether the authentication succeeds or fails, the request requests are allowed to be processed. If you need to control the access purpose of a specific authenticated user, you can inject authenticationsuccesshandler into it.

2.2 Peauth Bag

Support for authenticated scenarios--spring assumes that request requests have been approved by an externally configured system.

Authenticationdetailssource: Provides a getdetails () method for providing a authentication interface to specific Web request requests

J2eepreauthenticatedprocessingfilter: A filter based on the Java EE container authentication mechanism, which uses the principal name of the Java EE user as the principal for pre-completion authentication.

Webspherepreauthenticatedprocessingfilter: A WebSphere-certified filter that uses the WebSphere RunAs user principal name as the principal to complete the authentication first.

X509authenticationfilter: is responsible for processing requests that require unauthenticated users to provide client certificates. If the request contains a valid certificate, it will cause the subjectdnx509principalextractor to extract the security entity.

Requestheaderauthenticationfilter: A simple pre-authentication complete filter, which obtains the user name from the user's request header, used in such as CA siteminder system.

2.3 Session and Switchuser

Session Package: Provides a new authenticated user to handle session related behavior of the policy interface and implementation class

Switchuser Package: Provides an HTTP-based package with the ability to switch users. Similar to the SU command in Linux.

Sessionauthenticationstrategy: Allows pluggable support for httpsession-related behavior during a single authentication process. A typical application scenario is to confirm that the session exists or change the session ID to secure the session-based attack.

Switchuserfilter: High-privileged users switch to low-privileged users.

2.4 UI Package

Defaultloginpagegeneratingfilter: Used when a user does not have the login page configured. Used only when jumping to the login page.

2.5 www Package

Basicauthenticationfilter: The Basic Authentication header that handles an HTTP request and puts the result in Securitycontextholder.

In summary, the filter is responsible for processing HTTP request header messages with Basic authentication scheme and Base64 encoded Username:password token. For example, authenticate a user named "Aladdin" with the password "open sesame", Its head is as follows:

Authorization:basic qwxhzgrpbjpvcgvuihnlc2ftzq==

This filter can be used not only to provide basic authentication services for Remote protocol clients (such as Hessian and soap), but also to provide basic authentication services for standard user agents such as IE and Netscape. If the authentication succeeds, the authentication object of the authentication result will be put into securitycontextholder. If authentication fails and <ignoreFailure> is set to False (the default), the Authenticationentrypoint implementation class is called (unless the <ignoreFailure> property is set to true). Typically, Basicauthenticationentrypoint, which reminds users to re-certify with the Basic authentication method. It is a very attractive protocol due to the simple and extensive deployment of the Basic authentication protocol. However, because the Protocol passes passwords through explicit text, it does not apply to many scenarios. The digest certification provided by spring Security can replace the basic certification in these scenarios.

Note: If Remembermeservice is set, the filter will automatically return remember-me details to the user.

Digestauthenticationfilter: Refer to Basicauthenticationfilter, Note: Digest certification shortcomings, although digest certification method than the Basic authentication method more comprehensive and more secure, However, the fourth part of RFC2617 discusses the advantages of Digest authentication mode than the Basic authentication method, and also discusses the defects of Digest.

3.bind Module

Authenticationprincipal Annotations: Bind a method's arguments or methods to the authentication Getprincipal () method. You must indicate that the parameters should be resolved to the current user instead of the user who can edit the form. Examples are as follows:

@Controller  Public class Mycontroller {    @RequestMapping ("/user/current/show")     public  String Show (@ Authenticationprincipal customuser customuser) {         // do something with Customuser         return "View";     }

Authenticationprincipalargumentresolver: parsing authenticationprincipal annotations. The above example can also be done:

@Target ({elementtype.parameter}) @Retention (retentionpolicy.runtime) @AuthenticationPrincipal  public @Interface  CurrentUser {  }  @Controller  publicclass  Mycontroller {      @RequestMapping ("/user/current/show")      public  String Show (@CurrentUser customuser customuser) {          // do something with Customuser          return "View";      }

4. Contextual Context Module

Sync Securitycontextpersistencefilter: Get information from configured securitycontextrepository instead of request to Securitycontextholder, And the value is stored back into repository when the request finishes cleaning up the Contextholder (Httpsessionsecuritycontextrepository is used by default). Every request in the filter is executed only once, The filter needs to be executed before any authentication processing mechanism is in effect. The authentication processing mechanism, such as Basic,cas, is expected to get securitycontext from Securitycontextholder during execution.

Asynchronous Webasyncmanagerintegrationfilter: Provides integration of SecurityContext and Webasyncmanager. The way is through Securitycontextcallableprocessinginterceptor's beforeconcurrenthandling (Nativewebrequest, Callable) Method, SecurityContext is set to callable.

Securitycontextcallableprocessinginterceptor: Supports spring MVC callable integration. When Securitycontextcallableprocessinginterceptor executes Preprocess (nativewebrequest, callable) method, the injected SecurityContext is passed to Securitycontextholder.

    @Override    publicvoidthrows  Exception {        Securitycontextholder.setcontext (SecurityContext);    }

It is also clear that Securitycontextcallableprocessinginterceptor is executing postprocess (nativewebrequest, callable, Object) The Securitycontextholder method is called Clearcontext ().

    @Override    publicvoidthrows  Exception {        Securitycontextholder.clearcontext ();    }

5 CSRF Module

Cross-site requests forgery cross-site request forgery, also known as "one click Attack" or session riding, usually abbreviated as CSRF or XSRF, is a malicious use of the site.

Csrfexception: When a httpservletrequest does not have a valid Csrftoken or the exception that is thrown when there is no csrftoken, There are two sub-categories: Invalidcsrftokenexception and Missingcsrftokenexception.

Csrftoken provides a desired CSRF token information. The default implementation is Defaultcsrftoken, and there is an internal implementation class Saveonaccesscsrftoken.

Csrftokenrepository: Associate Crsftoken with HttpServletRequest so that it can correlate Csrftoken APIs. For example, you can store it in httpsesssion. The default implementation is httpsessioncsrftokenrepository.

Csrffilter: CSRF protection by using the synchronous token mode.

Csrflogouthandler is responsible for removing Csrftoken on exit. Called when in the Logout method in Logoutfilter:

             for (Logouthandler handler:handlers) {                handler.logout (request, response, auth);            }

6. Debug module

Debugfilter:spring Security's debug filter. To help users understand how request requests are handled by spring security, use a log to record messages such as session creation. Some other related messages are also recorded.

The logger encapsulates the Apache commons-logging.

7.firewall Module

An interface that Httpfirewall an interface to control the behavior of requests to prevent potential threats by encapsulating them.

Defaulthttpfirewall is the default implementation. The main check is whether a path is legitimate:

 /*** Checks Whether a path is normalized (doesn ' t contain path traversal sequences like "./", "/".     /"or"/. ") *     * @parampath the path to test *@returntrue if the path doesn ' t contain any path-traversal character sequences. */    Private Booleanisnormalized (String path) {if(Path = =NULL) {            return true; }         for(intj = Path.length (); J > 0;) {            inti = path.lastindexof ('/', j-1); intGap = J-i; if(Gap = = 2 && path.charat (i+1) = = '. ') {                //" .", "/./" or "/."                return false; } Else if(Gap = = 3 && path.charat (i+1) = = '. ' && Path.charat (i+2) = = '. ') {                return false; } J=i; }        return true; }

Firewalledrequest is an abstract class, which is the package that requests the request and returns a Httpfirewall interface. The difference is in the Reset method, which allows you to reset some or all of the state when the request leaves the security filter chain. The default implementation is Requestwrapper.

8. Header Module

Headerwriter is a convention that writes an HTTP request header to HttpServletResponse.

Headerwriterfilter adds a filter for the HTTP request header to the current request, adding a specific HTTP request header to the browser protection. such as x-frame-options (x-frame-options response header can be used to indicate whether the browser should be allowed to render in a page <FRAME> or <IFRAME>. To ensure that the site content is not embedded in other sites. ), x-xss-protection (under normal circumstances, through the following HTTP header, it is possible to close the page to send this header XSS protection feature. x-xss-protection:0) and x-content-type-options (this header is primarily used to prevent the MIME types from confusing attacks in IE9, Chrome, and Safari.) Firefox is still in dispute. Usually the browser can sniff the content itself to determine what type it is, rather than look at the Content-type value in the response. By setting X-content-type-options: If the Content-type matches the desired type, then no sniffing is required and only resources of the type determined can be loaded externally. )。

9.session Module

Concurrentsessionfilter: This filter has two functions. First: It calls Sessionregistry's Refreshlastrequest (String) method to ensure that the registered session usually has the correct last update time.

Second: It retrieves the sessioninformation from each requested sessionregistry and checks to see if the session has been marked as expired. If marked as expired, all logout handler (called in Logoutfilter) of the configuration are called, and the usual scenario is to expire the session. This will jump to the specified expiredurl,session expiration to generate a Httpsessiondestroyedevent event by registering the Httpsessioneventpublisher in <web.xml>.

10 Summary

Spring Security's support for Web security relies heavily on servlet filters. These filters intercept incoming requests and do some security processing before the application processes the request. Spring Security provides a number of filters that can intercept servlet requests and pass them on to authentication and Access Decision manager processing for enhanced security.

Reference documents:

1. http://www.ibm.com/developerworks/cn/java/j-lo-springsecurity/

2. Http://baike.baidu.com/link?url=mk6ZedYayBqvXehW094XdImcU9g2SGLgt-gmdKYAF17db97_mEloPPm3K-1eqqEymefNNO30b2CTGw2Ryf6amq

Spring security source analysis of the two---Web package analysis

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.