Spring Security: Description of core components

Source: Internet
Author: User
Tags access properties

Understanding the Spring Security Core component Description, the follow-up learning and use of spring security will no longer be a challenge.

1. Spring Security Core

Securitycontextholder , SecurityContext , authentication , Grantedauthority , Userdetails

Authentication: Represents the parties in spring security.

SecurityContext: Has the authentication, requests the related information.

Securitycontexthodler: Used to get securitycontext.

Grantedauthority: Represents the permissions granted to a party in the application.

Userdetails: User details. is actually a javabean.

Userdetailsservice:userdetails related business processes.

These are the core of spring security, and other APIs are built around these APIs, all of which serve them.

2, Identity authentication authentication

2.1, the General identity authentication

From the core part of spring security, there is a general concept of spring security, so how do you understand that?

Normally, our system is like this:

1, user input user name, password login

2, the system to verify the user name, password

3. Get user context information (role list, etc.)

4, get the relevant operation rights

For the top three above, it is handled with spring security:

1. The user name and password combination generates a authentication object (that is, the Usernamepasswordauthenticationtoken object).

2. The generated token object is passed to a AuthenticationManager object for validation.

3. After successful authentication, AuthenticationManager returns a authentication object.

4. Next, you can call

Securitycontexthodler.getcontext (). Setauthentication (...).

For a better understanding, here's an example:

 Packagecom.springsecurity.java.test;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.springframework.security.authentication.AuthenticationManager;Importorg.springframework.security.authentication.BadCredentialsException;ImportOrg.springframework.security.authentication.UsernamePasswordAuthenticationToken;Importorg.springframework.security.core.Authentication;Importorg.springframework.security.core.AuthenticationException;Importorg.springframework.security.core.GrantedAuthority;Importorg.springframework.security.core.authority.SimpleGrantedAuthority;ImportOrg.springframework.security.core.context.SecurityContextHolder; Public classAuthenticationexample {Private StaticSimpleauthenticationmanager samgr =NewSimpleauthenticationmanager ();  Public Static voidMain (string[] args) {Try {//user Input user name, password:BufferedReader in=NewBufferedReader (NewInputStreamReader (system.in)); System.out.println ("Please enter your username:"); String name=In.readline (); System.out.println ("Please enter your password:"); String Password=in.readline ();//The next step is the process of authenticating the system://1, the user name, password package into a tokenAuthentication Token=Newusernamepasswordauthenticationtoken (name, password);//2. Pass token to AuthenticationManager for identity authentication//3, the certification is complete, return to a certified identity:Authentication Result=samgr.authenticate (token);//after authentication, store in SecurityContext: Securitycontextholder.getcontext (). Setauthentication (result);      } Catch(Exception ex) {System.out.println ("Authentication failed"); } //read the identity of the authentication from SecurityContext:System.out.println (Securitycontextholder.getcontext (). Getauthentication ()); }} classSimpleauthenticationmanagerImplementsAuthenticationManager {Static FinalList<grantedauthority> authorities =NewArraylist<grantedauthority>(); Static{Authorities.add (NewSimplegrantedauthority ("Role_user")); }     PublicAuthentication Authenticate (authentication auth)throwsauthenticationexception {if(Auth.getname (). Equals (Auth.getcredentials ())) {return NewUsernamepasswordauthenticationtoken (Auth.getname (), auth.getcredentials (), authorities); }      Throw NewBadcredentialsexception ("Bad Credentials"); } } 
View Code

2.2. How to authenticate in the WEB application?

1, the user on the first page to click on a link

2, the background processing, the first to determine whether to access a protected resource

3, if it is a protected resource, determine whether the user is logged on, whether there is access to this resource

4. If the user is not logged in, return a login page to the user

5, user input username, password, and then login

6. Proceed to the identity verification process above

In the Web application environment, the above 1-4 processes are handled by Authenticationentrypoint.

How do I store a certified user?

When users want to access additional resources, it is necessary to determine whether there is access to the resource, in order to determine whether there is access rights, it is generally necessary for the user to log on to the system (to authenticate the identity of the user). If the user has successfully logged in, it is only necessary to determine if there is any access right.

In a generic Web application (without spring Security), we typically store user information in HttpSession.

What if spring security was added to the Web application system?

The same thing, or store this information in HttpSession. This is not the case for stateless RESTful Web service.

3. Authorization Authorization (Access Control)

The identity authentication authentication ensures that the user can access the system. Authority authentication (authorization guarantees that users can access resources in the system).

In a user's resource access, these two processes are not limited. Access control is the decision whether or not your request is allowed, and it is done before you access the resource after authentication.

User request--authentication----access to the resource and the response

The authentication process is handled by AuthenticationManager, and the authorization decision is handled by Accessdecisionmanager.

void Decide (authentication authentication, Object object, collection<configattribute>   Throws Accessdeniedexception, insufficientauthenticationexception;

Spring takes advantage of one of spring's core: AOP when it comes to licensing. In the previous period of research on AOP, AOP is generally embodied in the program as filter or interceptor, more of which is the use of interceptor.

The decide method above requires three parameters:

· Authentication is the authentication object that has been certified. The above study is already understandable.

· Object obj is a representation of a method call (methodinvocation) or request processing (action handler), as described in the next abstractsecurityinterceptor.

The configattributes is the associated feature configuration. This will be explained below.

Abstractsecurityinterceptor

The authorization section of security uses AOP, so you have to understand abstractsecurityinterceptor.

Interceptor generally provides an invoke method. This class is an abstract class that is not provided, uses its subclasses, and provides the Invoke method in subclasses. The second parameter in the Accessdecisionmanager decide method is the parameter Methodinvocation object of the Invoke method.

Configattribute

is actually configuring some of the access properties for an interceptor. As an example:

An interceptor Interceptor, configuration access properties have Role_a, Role_b, if a user is authenticated after he has a authentication for role_a, then his request will be the Interceptor interceptor processing.

The popular point is to set up a user's request that an interceptor can handle which identity.

Abstractsecurityinterceptor the execution process

1. Find out which configattributes are associated with the current request.

2. Submit Secure Object (which is the Methodinvocation object mentioned earlier), the current authentication (which is already authenticated), and the configattributes found in 1, Submitted to Accessdecisionmanager for authorization.

3, selectively change the identity of the user to verify. This is because of the diversity of user identities needed.

4. Secure object (Methodinvocation object execution), which is the execution of the handler we write in action.

5, if the configuration of Afterinvocationmanager, then Afterinvocationmanager will also be executed.

This process is documented in the official documentation and is already clear. To get a fresh look at the process, check out the source code:

In sub-class methodsecurityinterceptor of Abstractsecurityinterceptor:

 PublicObject invoke (methodinvocation mi)throwsThrowable {//Pre-processingInterceptorstatustoken Token=Super. Beforeinvocation (MI);        Object result; Try {//The real method call, which is the action call we wroteresult=mi.proceed (); } finally {            Super. Finallyinvocation (token); }//Afterinvocationmanager Processing        return Super. Afterinvocation (token, result); }


This code corresponds to the above process description, which should be 1, 2, and 3 in the process above that corresponds to the pre-processing part of the code. Just take a look at Beforeinvocation:

//The argument object is the method callprotectedInterceptorstatustoken beforeinvocation (Object object) {Assert.notnull (object,"Object was null"); Final Booleandebug =logger.isdebugenabled (); if(!Getsecureobjectclass (). IsAssignableFrom (Object.getclass ())) {            Throw NewIllegalArgumentException ("Security invocation attempted for object" +Object.getclass (). GetName ()+ "But Abstractsecurityinterceptor-only configured-to-support secure objects of type:" +Getsecureobjectclass ()); }//collection of feature configurations related to method callsCollection<ConfigAttribute> attributes = This. Obtainsecuritymetadatasource (). GetAttributes (object); if(Attributes = =NULL||Attributes.isempty ()) {            if(rejectpublicinvocations) {Throw NewIllegalArgumentException ("Secure object Invocation" + Object + "is denied as public invocations is not allowed via this interceptor. "+" This indicates a configuration error because the "+" R Ejectpublicinvocations property was set to ' true ' "); }             if(Debug) {Logger.debug ("Public object-authentication not attempted"); } publishevent (Newpublicinvocationevent (object)); return NULL;//no further work post-invocation        }         if(Debug) {Logger.debug ("Secure object:" + object + "; Attributes: "+attributes); }         if(Securitycontextholder.getcontext (). getauthentication () = =NULL) {Credentialsnotfound (Messages.getmessage ("Abstractsecurityinterceptor.authenticationnotfound",                    "An authentication object is not found in the SecurityContext"), object, attributes); }//get the authenticated identity of the userAuthentication Authenticated=authenticateifrequired (); //attempt Authorization        Try {           //authorization of the user This. Accessdecisionmanager.decide (authenticated, object, attributes); }        Catch(accessdeniedexception accessdeniedexception) {publishevent (Newauthorizationfailureevent (object, attributes, authenticated, accessdeniedexception)); Throwaccessdeniedexception; }         if(Debug) {Logger.debug ("Authorization Successful"); }         if(publishauthorizationsuccess) {publishevent (Newauthorizedevent (object, attributes, authenticated)); }//switch to another identity//attempt to run as a different userAuthentication RunAs= This. Runasmanager.buildrunas (authenticated, object, attributes); if(RunAs = =NULL) {            if(Debug) {Logger.debug ("Runasmanager did not change authentication object"); }             //no further work post-invocation            return NewInterceptorstatustoken (Securitycontextholder.getcontext (),false, attributes, object); } Else {            if(Debug) {Logger.debug ("Switching to RunAs Authentication:" +runAs); } securitycontext origctx=Securitycontextholder.getcontext ();            Securitycontextholder.setcontext (Securitycontextholder.createemptycontext ());             Securitycontextholder.getcontext (). Setauthentication (RunAs); //need to revert to token. Authenticated Post-invocation            return NewInterceptorstatustoken (Origctx,true, attributes, object); }    }

4, the internationalization of localization exception message

Spring security is divided into two processes of identity authentication and authorization, as stated above. In both of these processes, the occurrence of an exception is unavoidable. Spring provides international support for exception messages for this purpose.

Spring Security: Description of core components

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.