Springsecurity Implement login authentication and authorization authentication

Source: Internet
Author: User
Tags http request
Target

In the original company has a dedicated login authentication and Rights Management services, after the company in recent projects need to use spring security to implement the Distributed System user authentication authorization and permission verification function, so spent two days to study and implement the program:
Function Point Subdivision:
1. The login based on the rest request
2. User name password verification and verification of the successful user authorization
3. Permission configuration and validation for HTTP requests
4. Method-level permissions configuration and validation
5. analysis and implementation of user rights sharing in distributed environment one, rest request-based login 1.1 analysis

Spring security defaults to submitting user login requests through the form, which can be implemented by modifying the configuration to implement a custom login request 1.2

In Spring-security.xml, configure the login portal as follows, and configure the login URL in entry-point-ref (just focus on the Red Box callout section)

Note: The configuration will be described in the next two, the user name Password authentication and verification of the success of the user authorization 2.1 Analysis

The bottom of spring security is managed by a series of filter, and when we use namespace, Spring security automatically creates filterchain and the filter that is included by default. The position and function of several key filter are as follows, the complete information can be referenced (http://wiki.jikexueyuan.com/project/spring-security/filter.html)

filter position action
securitycontextpersistencefilter security_context_filter when request is in S Create a securitycontext
usernamepasswordauthenticationfilter form_login_filter Authentication and authorization processing, add a valid authentication for Securitycontextholder
FILTER Securityinterceptor security_context_filter protect Http resources to determine whether users have access to the appropriate resources

This shows that the function point is realized by Usernamepasswordauthenticationfilter. Usernamepasswordauthenticationfilter invokes the interface that AuthenticationManager handles the authentication request. AuthenticationManager will further entrust the request to authenticationprovider processing. Authenticationprovider calls Userdetailsservice for user details userdetails based on the requested user name. Spring Security has a built-in userdetailsservice implementation, such as: Cachinguserdetailsservice loading user details from the cache Jdbcdaoimpl loading user details from the database Inmemoryuserdetailsmanager loading user details from memory

None of this satisfies the needs of the current system, we need to invoke the interface of the user Service in the system to load the user details, so we need to define our own Userdetailsservice implementation. 2.2 Implementation

(1) Custom Userinfoservice implements the Userdetailsservice interface, overriding its Loaduserbyusername () method to implement loading user details from the interface of the user Service

(2) Configure the Usernamepasswordauthenticationfilter instance Authenticationfilter in Spring-security.xml and inject a custom userdetailsservice instance into it userinfo Service.

(3) Replace the default authentication filter in Filterchain with Authenticationfilter Usernamepasswordauthenticationfilter

The default FILTER in Filterchain has its own location, and the usernamepasswordauthenticationfilter corresponds to Form_login_filter. Spring security supports specifying a location for custom filter placement via position, before, or after. The meaning of the statement in the red box is to place the authenticationfilter in the Form_login_filter position, which also implements the function of replacing the default usernamepasswordauthenticationfilter.

(4) The entire user authentication and authorization process is as follows:

Note: The partial implementation of the "User rights sharing in distributed Environment" feature in the Red Box section, followed by three, permission configuration and validation of HTTP requests 3.1 analysis

The permission configuration for an HTTP request is the corresponding relationship between the custom URL and the required permissions. Implemented in the configuration file
The permission validation for an HTTP request is to check that the user's permissions acquired by the user's logon authorization phase can access the URL. Spring security Filtersecurityinterceptor by invoking the corresponding interface of Accessdecisonmanager to complete the authentication of permissions, where Accessdecisonmanager or configuring one or more Accessdecisionvoter vote () methods to vote (successful return 1, failed return-1), And according to each Accessdecisionvoter poll results and a certain policy determines whether the user has permission to access the URL. Spring Security uses the Accessdecisonmanager implementation class affirmativebased policy by default as long as there is a accessdecisionvoter voted against (that is, the vote method returns-1), Access to the URL is denied. Spring Security also has a number of accessdecisionvoter implementation classes, which describe two commonly used accessdecisionvoter:webexpressionvoter based on expression-matching voting methods, That is, as long as the user right to include the URL required permission to vote in favor of the vote rolevoter similar to webexpressionvoter but need to configure the permission prefix, the default prefix is Role_ 3.2 implementation

(1) Configure the URL and its permissions in Spring-security.xml

The meaning of a red box statement is to configure ROLE_DICT permissions for URL requests that can match "/dicts**" expressions

(2) The filter filtersecurityinterceptor of the permission check and its configuration are all using the spring security default configuration.

(3) The complete process for a non-logon HTTP request is as follows:

Note: The partial implementation of the "User rights sharing in distributed Environment" feature in the Red Box section, followed by four, method-level permissions configuration and Validation 4.1 analysis

Can be implemented based on annotations, reference http://blog.csdn.net/w605283073/article/details/51327182 4.2 implementation

(1) Opening @preauthorize annotation support in Spring-security.xml

(2) Add @preauthorize annotations for methods that require permission validation v. User rights sharing in distributed environments 5.1 analysis

The current distributed system has implemented a REDIS-based distributed session, which is a shared session between different services on different hosts during the same visit. So when we need to implement user rights sharing, we just have to write the user details (including user permissions) to the session during the login verification phase. Through the "User authentication and authorization process" in the previous section, it is known that the user details of the user's verification are encapsulated as authentication instances and written to securitycontext, so we simply write the SecurityContext to the shared session. Where you need to use user rights (such as a URL to access a specific permission or the validation phase of a method), you only need to remove the SecurityContext 5.2 implementation from the session

(1) Customizing the Authenticationsuccesshandler implementation class Sessionauthenticationsuccesshandler, overriding the Onauthenticationsuccess () method, Save SecurityContext to session

(2) in Spring-security.xml for login Authentication Authorization filter Authenticationfilter Configure authorization after successful processing handler to Sessionauthenticationsuccesshandler

(3) Custom filter validationfilter, implemented in the Dofilter () method to remove the SecurityContext saved in the session to Securitycontextholder

(4) Add Validationfilter to default Filterchian in Spring-security.xml, located in Filtersecurityinterceptor (location filter_security_ Interceptor), which allows you to save SecurityContext in the session to Securitycontextholder by Validationfilter before permission validation

The Before keyword is used here to define the insertion position of the Validationfilter

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.