Spring Security: Core Components
After understanding the core components of Spring Security, it is no longer difficult to learn and use Spring Security in the future. 1. Spring Security core SecurityContextHolder, SecurityContext, Authentication, GrantedAuthority, and UserDetails Authentication: represents the clients in Spring Security. SecurityContext: Has Authentication and request-related information. SecurityContextHodler: used to obtain SecurityContext. GrantedAuthority: the permissions granted to the client in the application. UserDetails: User details. It is actually a JavaBean. UserDetailsService: business processing related to UserDetails. These are the core of Spring Security. Other APIs are built around these APIs and serve them. 2. Identity Authentication 2.1. General identity Authentication involves a general concept of Spring Security from the core part of Spring Security. How can we understand the above? In general, our system is like this: 1. the user enters the user name, Password Logon 2. The system verifies the user name and password 3. obtains the user context information (role list, etc) 4. Get the relevant operation permissions for the first three mentioned above, which are handled by Spring Security: 1. generate an Authentication object (that is, UsernamePasswordAuthenticationToken object) by combining the user name and password ). 2. The generated token object is passed to an AuthenticationManager object for verification. 3. After successful Authentication, AuthenticationManager returns an Authentication object. 4. Next, you can call SecurityContextHodler. getContext (). setAuthentication (...). For better understanding, the following is an example: copy the code package com. springsecurity. java. test; import java. io. bufferedReader; import java. io. inputStreamReader; import java. util. arrayList; import java. util. list; import org. springframework. security. authentication. authenticationManager; import org. springframework. security. authentication. badCredentialsException; import org. springframework. security. authentication. usernamePasswordAuthent IcationToken; import org. springframework. security. core. authentication; import org. springframework. security. core. authenticationException; import org. springframework. security. core. grantedAuthority; import org. springframework. security. core. authority. simpleGrantedAuthority; import org. springframework. security. core. context. securityContextHolder; public class AuthenticationExample {private static Simpl EAuthenticationManager samgr = new SimpleAuthenticationManager (); public static void main (String [] args) {try {// enter the user name and password: BufferedReader in = new BufferedReader (new InputStreamReader (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 process of identity authentication by the system: // 1. encapsulate the user name and password Generate a token Authentication token = new UsernamePasswordAuthenticationToken (name, password); // 2. Pass the token to AuthenticationManager for identity Authentication // 3. After the Authentication is complete, return an authenticated identity: authentication result = samgr. authenticate (token); // after authentication, it is stored in SecurityContext: SecurityContextHolder. getContext (). setAuthentication (result);} catch (Exception ex) {System. out. println ("authentication failed");} // read the authenticated identity from SecurityContext: System. out. println (Secur ItyContextHolder. getContext (). getAuthentication ();} class SimpleAuthenticationManager implements AuthenticationManager {static final List <GrantedAuthority> AUTHORITIES = new ArrayList <GrantedAuthority> (); static {AUTHORITIES. add (new SimpleGrantedAuthority ("ROLE_USER");} public Authentication authenticate (Authentication auth) throws AuthenticationException {if (auth. getName (). equals (auth. GetCredentials () {return new UsernamePasswordAuthenticationToken (auth. getName (), auth. getCredentials (), AUTHORITIES);} throw new BadCredentialsException ("Bad Credentials");} How do I perform identity authentication in code 2.2 and Web applications? 1. When you click a link on the homepage 2. When processing in the background, first determine whether a protected resource is to be accessed. 3. If a protected resource is used, determine whether the user is logged on, whether the resource has access permissions 4. If the user does not log on, return a logon page to the user 5. enter username and password, next, log on to the website. Next, start the authentication process. In the Web Application environment, AuthenticationEntryPoint processes the 1-4 process. How to store authenticated users? When a user wants to access another resource, he must determine whether the user has the access permission for the resource. before determining whether the user has the access permission, generally, You need to log on to the system first (to authenticate the user's identity. If the user has successfully logged on, you only need to determine whether there is access. In general Web applications (without Spring Security), we usually store user information in HttpSession. What if Spring Security is added to the Web Application system? The procedure is similar. You can store the information in HttpSession. This is not the case for stateless RESTful Web Services. 3. Authorization (Access Control) Authentication ensures that users can Access the system. Permission authentication (authorization ensures that users can access resources in the system ). These two processes are indispensable for a user's resource access. Access Control determines whether your request is permitted. It is performed after identity authentication and before accessing the resource. User requests --> Identity Authentication --> authorization --> resource access --> the process of responding to identity authentication is handled by AuthenticationManager, and authorization decisions are handled by AccessDecisionManager. Void decide (Authentication authentication, Object object, Collection <ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException; Spring makes full use of AOP, one of the core components of Spring. Through the research on AOP some time ago, AOP is generally reflected as a Filter or Interceptor in the program, and most of them use Interceptor. The preceding decide method requires three parameters: · Authentication is an authenticated Authentication object. The above learning is understandable. · Object obj indicates a method call or a Handler of an Action, which is described in the following AbstractSecurityInterceptor. · ConfigAttributes is the related feature configuration. The following is a description. The authorization section in AbstractSecurityInterceptor Security uses AOP, so you have to understand AbstractSecurityInterceptor. Interceptor generally provides the invoke method. This class is an abstract class that is not provided. It is used as its subclass and the invoke method is provided in the subclass. The second parameter in the AccessDecisionManager's decide method is the MethodInvocation object of the invoke method. ConfigAttribute is to configure some access attributes for an interceptor. For example, an interceptor configures the access attributes ROLE_A and ROLE_ B. If a user passes Authentication, the Authentication is ROLE_A, the request will be processed by the interceptor. In other words, the common point is to set the identities of user requests that an interceptor can process. The execution process of AbstractSecurityInterceptor 1. Find out which configAttributes are associated with the current request. 2. Submit the secure object (that is, the MethodInvocation object mentioned above), the current Authentication (that is, the authenticated identity), and The configAttributes found in 1 to AccessDecisionManager for authorization. 3. selectively change the user's identity for verification. This is because of the diversity of user identities. 4. Secure Object (methodInvocation Object execution), that is, the Handler written in the action. 5. If AfterInvocationManager is configured, AfterInvocationManager will also execute. This process is described in the official document and is clear. To learn more about this process, check the source code: In the MethodSecurityInterceptor subclass of AbstractSecurityInterceptor: copy the public Object invoke (MethodInvocation mi) code) throws Throwable {// pre-process interceptorstatuen en token = super. beforeInvocation (mi); Object result; try {// real method call, that is, the action we write calls result = mi. proceed ();} finally {super. finallyInvocation (token);} // afterInvocationManager processes return super. afterInvocation (token, result );} Copy the code, which corresponds to the preceding process description. The steps 1, 2, and 3 correspond to the pre-processing part of the code. Let's take a look at beforeInvocation: copy the code // The parameter object is the method call protected InterceptorStatusToken beforeInvocation (Object object) {Assert. notNull (object, "Object was null"); final boolean debug = logger. isDebugEnabled (); if (! GetSecureObjectClass (). isAssignableFrom (object. getClass () {throw new IllegalArgumentException ("Security invocation attempted for object" + object. getClass (). getName () + "but cannot actsecurityinterceptor only configured to support secure objects of type:" + getSecureObjectClass ());} // collect Collection of feature configurations related to method calls <ConfigAttribute> attributes = this. obtainSecurityMetadataSource (). getAttributes (object); if (attributes = null | attributes. isEmpty () {if (rejectPublicInvocations) {throw new IllegalArgumentException ("Secure object invocation" + object + "was denied as public invocations are not allowed via this interceptor. "+" This indicates a configuration error because the "+" rejectPublicInvocations property is set to 'true' ");} if (debug) {logger. debug ("Public object-authentication not attempted");} publishEvent (new PublicInvocationEvent (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 was not found in the SecurityContext "), object, attributes);} // obtain the authenticated identity Authentication authenticated = authenticateIfRequired (); // Attempt authorization try {// perform user authorization this. accessDecisionManager. decide (authenticated, object, attributes);} catch (publish events) {publishEvent (new AuthorizationFailureEvent (object, attributes, authenticated, AccessDeniedException); throw events;} if (debug) {logger. debug ("Authorization successful");} if (publishAuthorizationSuccess) {publishEvent (new AuthorizedEvent (object, attributes, authenticated ));} // switch to another identity // Attempt to run as a different user Authentication 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 new InterceptorStatusToken (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 new InterceptorStatusToken (origCtx, true, attributes, object );}}