spring  Security Learning Summary

Source: Internet
Author: User
Tags event listener ldap md5 encryption



Tips:
All of the certification provider implementations provided by Springsecurity are Org.springframework.security.providers.AuthenticationProvider
Interface implementation class, they all implement the Authenticate method of this interface, if you are looking at the source code, you will find this authenticate method in fact and authe
The Authenticate method for the Nticationmanager (authentication manager) interface is exactly the same.



The Providers property defines a collection of provider managers, Providermanager (provider manager) walks through the collection of this authentication provider and invokes the authenticate method of the provider. If one provider fails to authenticate, another provider is tried until a certain authentication provider is able to successfully verify the identity of the user in order to secure authentication from a different source. The following table lists some of the system-provided authentication providers:

MentionFor Stakeholders
ForUse

DaoauthenticationprovideR
To verify identity by reading user information from the database

AnonymousauthenticationpRovider
Anonymous user authentication

RemembermeauthenticationProvider
Authentication of user information in saved cookies

Authbyadapterprovider
Verifying identities using the container's adapter

CasauthenticationprovideR
Authenticate with Yale Center authentication Service for single sign-on

JaasauthenticationprovidEr
Obtaining user information authentication from the Jass login configuration

RemoteauthenticationprovIder
Authenticating users based on remote services

RunasimplauthenticationpRovider
Authenticating a user who has been replaced by the manager

X509authenticationprovidEr
Obtaining user information verification identity from X509 authentication

TestingauthenticationproVider
Unit tests are used





















As can be seen from the table above, the system provides us with different certification providers, each of which certifies the certification information that it has specified, such as DaoauthenticationprovideR only for UsernamepasswordauthentiCationtoken This certificate information for certification.

In the actual project, the user's identity and permissions information may be stored in different security systems (such as databases, LDAP servers, CA centers).
As programmers, we can choose different authenticationprovider (certification providers) as needed to provide authentication services to our own systems.

Here we highlight DaoauthenticationprovideR, which reads the user information from the database to verify the identity, configured as follows:

1< beansId= "DaoauthenticationprovideR
Class= "Org.springframework.security.providers.dao.DaoAuthenticationProvideR
2P:passwordencoder-ref = "Passwordencoder"
3P:userdetailsservice-ref = "Userdetailsservice"/>
4< beansId= "Passwordencoder"
5class= "Org.springframework.security.providers.encoding.Md5PasswordEncoder"/>
Remember the remembermeservices you configured earlier? It also has a and daoauthenticationprovideR the same attribute Userdetailsservice, which is an interface provided by the system (Org.springframework.security.userdetails.UserDetailsService), Here we put it in a separate presentation.

First we need to understand another important component that Springsecurity provides for us, the Org.springframework.security.userdetails.UserDetails interface, which represents a user of an application system, This interface defines the methods associated with user security information:

String getusername (): Gets the user name;

String GetPassword (): Gets the password;

Boolean isaccountnonexpired (): Whether the user account expires;

Boolean isaccountnonlocked (): User account is locked;

Boolean iscredentialsnonexpired (): Whether the user's credentials expire;

Boolean isenabled (): Whether the user is in an active state.

User credentials are considered invalid when any of the above methods that determine the state of the user return false. The Userdetails interface also defines the Getauthorities () method that gets the user's permission information, which returns a grantedauthority[] Array object, grantedauthority is the user rights information object, This object defines a getauthority () method that obtains user permission description information.

Userdetails can be returned from the database or returned from other, such as LDAP, depending on what is used in your system to store user information and permissions and the corresponding authentication provider. Here we are only focusing on daoauthenticationprovideR (the provider who obtains user authentication information from the database), I have limited level, have not had the opportunity to use other providers in the project. In this case, where is the userdetails that encapsulates the user's details? This is the Userdetailsservice interface that we are going to introduce, which only defines the unique Userdetailsloaduserbyusername (String username) method, It uses the user name to get the entire userdetails
Like.

You may be a little confused to see here, because the authentication object mentioned above also holds the user's authentication information, it is important to note that the authentication object is the security access control user Information security object that Spring secure uses. In fact, the authentication object has both an unauthenticated and authenticated state, which is an unauthenticated object when passed in as a parameter to the Authenticate method of the authentication Manager (AuthenticationManager). It obtains the user's identity information (such as user name, password) from the client, either from a login page or from a cookie, and is automatically constructed as a authentication object by the system. The userdetails mentioned here represents the source of a user's security information (returned from the database, LDAP server, CA Center), and what Spring security does is to match this unauthenticated authentication object with the Userdetails. After success, the user rights information in Userdetails is copied into authentication to form a complete authentication object, shared by other components.

In this way, we can get information about the user in the system, and we need to use the Objectgetprincipal () method defined by the authentication object, which returns an object of Type objects, which can usually be converted to Userdetails So that you can get information such as user name, password, and permissions. The code is as follows:

1Userdetails Details=(userdetails) Authentication.getprincipal ();
2
3Grantedauthority[] Authority=Details.getauthorities ();
The Daoauthenticationprovide is described earlierR, it can read the user information from the database, also can be read from a user properties file, in the next article we describe how to read the user information from the database, of course, will also involve more in-depth things, such as the needs of their own system to customize Userdetails And Userdetailsservice, this just lets you have a simple understanding of the entire system, so we use the user properties file (users.properties) to store user information:

1admin = admin,role_supervisor
2
3User1 = User1,role_user
4
5User2 = User2,role_user
6
7User3 = User3,disabled,role_user
Configuration Userdetailsservice:

1< beansId= "Userdetailsservice"
2
3class= "Org.springframework.security.userdetails.memory.InMemoryDaoImpl" >
4< propertyName = "UserProperties" >
5< beansClass= "Org.springframework.beans.factory.config.PropertiesFactoryBean"
6P:location = "/web-inf/users.properties"/>
7</Property >
8 </Bean >
The Inmemorydaoimpl class is an implementation of the Userdetailsservice interface that reads user information from the properties file. Springsecurity uses a property editor to organize the user information for us into an object of the Org.springframework.security.userdetails.memory.UserMap class, and we can also provide a list of user rights information directly, as described in Applicationcontext-security.xml configuration file.

Each line of the UserMap string is represented as a key-value pair, preceded by a user name, followed by an equal sign, followed by information such as the password/permission given to the user, separated by commas. Like what:

1admin = admin,role_supervisor
Defines a user login password named admin, which has role_supervisor permissions, and a user login password named User3 that is configured in the Users.properties file is User3, and the user has Role_user permissions , disabled defines that the user is not available for activation (Userdetails's IsEnabled method).

Even developers of the system, or end-users, should not see plaintext passwords in the system. So, springsecurity consideration is still very thoughtful, provide us with the password encryption function. As you are in the DAO certification provider (daoauthenticationprovideR), the Passwordencoder property is configured with a password encryption program (cipher encoder). Here we use MD5 encryption, can see
The Scott user in the configuration file, can you see what his password is? Of course, this is just a demo function, other users have not changed, you can try it yourself. The system provides us with some common cipher encoders (these encoders are located under the Org.springframework.security.providers.encoding package):

Plaintextpasswordencoder(default)--Do not encode the password, directly return the unchanged password;

Md4passwordencoder--A message digest (MD4) encoding of the password;

Md5passwordencoder--A message digest (MD5) encoding of the password;

Shapasswordencoder--Encode the password in a secure hash Algorithm (SHA).

You can select the appropriate cipher encoder as needed, and you can also set the seed source for the encoder (salt source). A seed source provides a seed (salt) for encoding, or a coded key, which is not described here.

There are a lot of things attached here, I hope you have not forgotten in the AuthenticationManager (authentication manager) also configured a bean named Sessioncontroller, This bean prevents the user from having a successful login after a successful login. In the Applicationcontext-security.xml configuration file, add the Sessioncontroller configuration:

1< beansId= "ConcurrentsessioncontrolLer
2
3Class= "Org.springframework.security.concurrent.ConcurrentSessionControlLerimpl "
4P:maximumsessions = "1"
5 P:exceptionifmaximumexceeded = "true"
6P:sessionregistry-ref = "Sessionregistry"/>
7< beansId= "Sessionregistry"
8
9class= "Org.springframework.security.concurrent.SessionRegistryImpl"/>
The Maximumsessions property is configured to allow only one user to log on to the system once, exceptionifmaximumexceedThe Ed property configures whether the first logon is invalidated when a second logon is made. Setting this to true does not allow a second logon. For this feature to work, we also need to add a listener to the Web. xml file to allow Springsecurity to get the session lifecycle event, configured as follows:

1< listener>
2< Listener-class >
3Org.springframework.security.ui.session.HttpSessionEventPublisheR
4</Listener-class >
5 </Listener >
HttpsessioneventpublisheThe R class implements the Javax.servlet.http.HttpSessionListener interface, when the session is created by calling ApplicationContext's Publishevent ( Applicationevent event) publishes events of type Httpsessioncreatedevent, The Httpsessioncreatedevent class inherits from the subclass of the Org.springframework.context.ApplicationEvent class HttpsessionapplicationevENT abstract class.

ConcurrentsessioncontrolLer uses Sessionregistry to complete the processing of the life cycle events of the released session, Org.springframework.security.concurrent. Sessionregistryimpl (implements the Sessionregistry interface), the Sessionregistryimpl class also implements the spring The framework's event listener Org.springframework.context.ApplicationListener interface, and implements the Onapplicationevent defined by the interface (applicationevent Event) method to handle events of type Applic ationevent, if you understand Springframework event handling, then you should be able to understand it well here.

Certification Manager to this end, the certification process filter is also introduced, then we continue to introduce the filter chain of the next filter
SecuritycontextholderawaRerequestfilter:

1< beansId= "SecuritycontextholderawaRerequestfilter "
2Class= "Org.springframework.security.wrapper.SecurityContextHolderAwaRerequestfilter "/>
This filter uses decorative mode (decorate model) to decorate the HttpServletRequest object. Its wapper is ServletRequest packaging class HttpservletrequestwrappeSub-class of R (e.g. Savedrequestawarewrapperor SecuritycontextholderawaRerequestwrapper), attach the method of obtaining user rights information, request parameters, headers and cookies.

RemembermeprocessingfiltER filter configuration:

< Bean id = "RemembermeprocessingfiltEr

class = "Org.springframework.security.ui.rememberme.RememberMeProcessingFiltEr

P:authenticationmanager-ref = "AuthenticationManager"

P:remembermeservices-ref = "Remembermeservices"/>

When authentication user authorization information does not exist in Securitycontextholder, remembermeprocessingfiltER will call Remembermeservices's Autologin () method to get the user information from the cookie automatically login.

AnonymousprocessingfilteR Filter Configuration:

1< beansId= "AnonymousprocessingfilteR
2Class= "Org.springframework.security.providers.anonymous.AnonymousProcessingFilteR
3P:key = "Springsecurity"
4P:userattribute = "Anonymoususer,role_anonymous"/>
If there is no authorization information, the anonymous user is automatically added to Securitycontextholder, which is the userattribute configured here, and the system assigns a role_anonymous permission to the user.

ExceptiontranslationfiltER (Exception handling filter), which is used to handle exceptions thrown during the system authentication authorization process, mainly dealing with accessdeniedexception and authenticationexception two exceptions and jumping to different URLs according to the configuration:

1< beansId= "ExceptiontranslationfiltEr
2Class= "Org.springframework.security.ui.ExceptionTranslationFiltEr
3P:accessdeniedhandler-ref = "Accessdeniedhandler"
4 P:authenticationentrypoint-ref = "Authenticationentrypoint"/>
5<!--Handling Accessdeniedexception-
6 < BeansId= "Accessdeniedhandler"
7Class= "Org.springframework.security.ui.AccessDeniedHandlerImpl"
8 P:errorpage = "/accessdenied.jsp"/>
9 < BeansId= "Authenticationentrypoint"
10Class= "org.springframework.security.ui.webapp.AuthenticationProcessingFilterentrypoint "
11P:loginformurl = "/login.jsp"
12P:forcehttps = "false"/>
The Accessdeniedhandler is used to handle the accessdeniedexception exception that is thrown when the user does not have permission to access the currently requested resource and jumps from the/ACCESSDENIED.JSP page configured here.

Authenticationentrypoint(Authentication entry point), where the user login page is defined. The system provides us with the implementation of 3 authentication entry points:

Authentication entry Point
ForUse

BasicprocessingfilterentRypoint
By sending a HTTP401 (unauthorized) message to the browser, a browser pops up the login dialog box prompting the user to log in

AuthenticationprocessingFilterentrypoint
redirect users to an HTML form-based login page

CasprocessingfilterentryPoint
Redirect users to a Yale CAS login page


Here we use authenticationprocessingFilterentrypoint Authentication entry point, provide users with a friendly login interface, just to give users a better experience.

FiltersecurityinterceptoR (Filter security Interceptor), which first invokes the authentication manager to determine if the user has been successfully authenticated and redirects to the login interface if not verified. Otherwise, obtain the user's permission information from authentication, and then obtain the permissions for the URL from the Objectdefinitionsource. Finally call Accessdecisionmanager (Access Decision manager) to determine whether the user currently has permissions that match the permissions of the currently protected URL resource, and if so, to access the URL resource, otherwise it will be thrown accessdeniedexception Exception and returns a 403 error for the client browser (if the user-defined accessdenied page is redirected to the page, see: Exception Handling Filter exceptiontranslationfiltER is configured in Accessdeniedhandlerbean), the working mechanism of Access decision management will be described in more detail later, here first the filter security interceptor configuration is as follows:

1<beanid = "FiltersecurityinterceptoR
2
3Class= "Org.springframework.security.intercept.web.FilterSecurityInterceptoR
4
5P:authenticationmanager-ref = "AuthenticationManager"
6
7P:accessdecisionmanager-ref = "Accessdecisionmanager" >
8 < propertyName= "Objectdefinitionsource" >
9< value ><! [cdata[
10
11Convert_url_to_lowercase_before_comparison
12Pattern_type_apache_ant
13 /admins/**=role_supervisor
14/user/**=role_user,is_authenticated_remembered
15/default.jsp=role_user,is_authenticated_remembered
16 /**=is_authenticated_anonymously
17]]> </value >
18</Property >
</Bean >
As can be seen from the configuration, the filter security interceptor is used in the authentication manager that we configured earlier, the filter security Interceptor uses AuthenticationManager and invokes its providers (provider list) to authenticate the user and obtain the permissions that the user has. If the user is successfully authenticated, the filter security interceptor will use Accessdecisionmanager (Access Decision manager) to determine whether authenticated users have access to protected resources, which are defined by the Objectdefinitionsource attribute.

Access Decision Manager (Accessdecisionmanager):

1<beanid = "Accessdecisionmanager"
2class = "org.springframework.security.vote.AffirmativeBased"
3 P:allowifallabstaindecisioNS = "false" >
4< propertyName = "Decisionvoters" >
5 < list >
6< beansclass= "Org.springframework.security.vote.RoleVoter"/>
7 < beansclass= "Org.springframework.security.vote.AuthenticatedVoter"/>
8</list >
9</Property >
10</Bean >
Authentication is only the first step in the springsecurity security mechanism, and the Access Decision manager verifies that the user has access to the appropriate resource (FiltersecurityinterceptoThe Objectdefinitionsource property defines the property information required by the access URL in R.

The org.springframework.security. Accessdecisionmanager interface defines a decide method for verifying that a user has access to a protected resource. Another supports method determines whether the access Decision manager can make access decisions against the resource, depending on the configuration properties of the protected resource, that is, the permissions required to access those resources. The Decide method ultimately determines whether or not the user has access rights, and if not, throws a Accessdeniedexception exception (as mentioned before, you should look back at it).

spring&nbsp; Security Learning Summary

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.