Overcoming your negative, obsessive, distorted way of thinking can increase your productivity and self-esteem
Filter-servletsecurity integration at the code level: WebSecurityConfiguration2. Security implementation flow chart 3. Security Oauth2 principle component cognitive TokenEndpoint: TokenGranter: TokenServices: code level cognition: Security Oauth2 Flow chart Of obtaining tokens Interface request flow Chart 5. conclusion
1. Basic knowledge
To understand Security Oauth2 we need to understand Security; To understand Security, we need to do some basic understanding of Security components.
Knowledge of Security components
-
SecurityContextHolder: Stores Security context information. After Spring Security’s verification, the authentication information is stored in the SecurityContext
-
Authentication: In the Security field, the user password is called Authentication instead of the user password. Authentication is the highest level of identity/Authentication abstraction in Spring Security. When in Rome, do as the Romans do. When in Rome, do as the Romans do. For example, we often use the [clientId, clientSecret] [username, password] can be encapsulated into a UsernamePasswordAuthenticationToken (Authentication)
-
AuthenticationManager: At the component level, this component is used to verify Authentication. The common implementation class is ProviderManager. But at the code level, ProviderManager leaves the validation to another component, AuthenticationProvider. Maintain a List in the ProviderManager, find the AuthenticationProvider that supports the current Authentication through traversal, and hand it over for Authentication. (See AuthenticationManager as the main conduit.)
-
AuthenticationProvider: the component that actually verifies Authentication at the code level mentioned above. Common AuthenticationProviders are
: (1) DaoAuthenticationProvider Dao type certification Provider, to retrieve information from a database and compare the submitted information, complete the certification.
(2) AnonymousAuthenticationProvider: anonymous authentication Provider
-
UserDetails: To understand UserDetails, we can compare it to Authentication. Authentication is the encapsulation of the data submitted by the user. UserDetails is the encapsulation of the user information obtained from the data layer.
-
UserDetailsService: DaoAuthenticationProvider certifier fetch the data from the database layer is done through UserDetailsService, take to be populated UserDetails. Common UserDetailsService
(1.JdbcDaoImpl
(2) ClientDetailsUserDetailsService: query populated UserDetails [clientId, clientSecret] form
Filter-Servlet
We all know that requests go through the Filter chain to the Servlet
The process looks something like this
The Security principle
Keep in mind that Spring Security, in web applications, comes in through filters.
To intervene in the body ApplicationFilterChain, we introduce a special Filter,
DelegatingFilterProxy:
This Filter is interesting because it has a Filter delegate property inside that acts as a proxy for another Filter. When the request is executed to DelegatingFilterProxy, the Delegate Filter is called. DelegatingFilterProxy can be thought of as a Filter that bends a Filter chain
FilterChainProxy:
Is also a Filter, the Security is by putting his Settings to DelegatingFilterProxy. The delegate FilterChain properties come up in the body. However, from its name, it is also a proxy FIlter
He internal maintains a List < SecurityFilterChain > filterChains to represent different permissions url corresponding to different filter chain, but a request only up to a SpringSecurityFilterChain chain.
SpringSecurityFilterChain:
FilterChainProxy traverses the List
filterChains to match a SecurityFilterChain that is appropriate for the current request and then the chain call is made.
Security Common Filter:
-
SecurityContextPersistenceFilter: located in the top of the SecurityFilterChain. In the past, session was used to store user information. After using the Security framework, the user logs in once and is identified by the sessionId. The user information is stored in the SecurityContextHolder. This process of put SecurityContextPersistenceFilter is completed. SecurityContextPersistenceFilter main job creating SecurityContext security context information and request at the end of the empty SecurityContextHolder (with the try, finally combination)
-
UsernamePasswordAuthenticationFilter: forms authentication is the most commonly used way of a certification, allowed to form input user name and password to log in. It will encapsulate [username,password] as Authentication and hand it to authenticationManager for Authentication. AuthenticationManager will select a provider. The UserDetailsService obtains the UserDetail of the data that stores user information from the data level such as redis and mysql through the UserDetailsService and compares it with Authentication. Authentication success
-
ExceptionTranslationFilter: Abnormal transformation filter is located in the whole springSecurityFilterChain rear, mainly deal with two exceptions, AccessDeniedException access and AuthenticationException certification anomaly. Depending on the configuration and exception type, you can choose to jump to the login page, or 404, 405.
Code level integration:
The most important use of Security in code is @enableWebSecurity. This is an important annotation for code integration with Security. Let’s take a look
Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
SpringWebMvcImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
boolean debug(a) default false;
}
---
@Import(AuthenticationConfiguration.class)
@Configuration
public @interface EnableGlobalAuthentication {
}
Copy the code
The job of the @enableWebSecurity annotation is to activate three classes
- Does it include for springmvc SpringWebMvcImportSelector: determine the current environment
- WebSecurityConfiguration: Configures Web security
- AuthenticationConfiguration: configuration certification related to core classes, mainly responsible for generating global authentication manager the AuthenticationManager
The most important is WebSecurityConfiguration
WebSecurityConfiguration
Before that, here is a tip for reading the source code of the Spring-related framework
XxConfiguration: A configuration file in this format, which we can think of as a bean.xml file, outputs beans to the container
XxConfigurer: The configuration file in this format is usually obtained by xxConfiguration. The xxConfiguration file extracts the configuration from xxConfigurer and processes the configuration in xxConfiguration.
To summarize: xxConfiguration collects N related xxConfigurer files into this class and parses them into a single xxConfiguration file for the container output Bean.
Ok, let me look at the WebSecurityConfiguration
public class WebSecurityConfiguration implements ImportAware.BeanClassLoaderAware {
// Collect SecurityConfigurer into this class and parse it.
private List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers
/ / output springSecurityFilterChain bean
@Bean(name = "springSecurityFilterChain";)
public Filter springSecurityFilterChain(a) throws Exception {
booleanhasConfigurers = webSecurityConfigurers ! =null
&& !webSecurityConfigurers.isEmpty();
if(! hasConfigurers) {
WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() {
});
webSecurity.apply(adapter);
}
return webSecurity.build();/ / build named FilterChainProxy
}
}
Copy the code
Two important points:
- Collect the associated SecurityConfigurer: We integrated security, usually inherited WebSecurityConfigurerAdapter do security configuration, Realized SecurityConfigurer WebSecurityConfigurerAdapter itself, so that the configuration information will be parsed to WebSecurityConfiguration configuration class, role to the security. So that’s why we need to implement a WebSecurityConfigurerAdapter to configure security policy.
- Output (named FilterChainProxy) springSecurityFilterChain bean: so even on the dock with the theme FilterChain code level. (springSecurityFilterChain creation process are interested in can tell the code)
WebSecurityConfigurerAdapter adapter pattern of use, so that we can realize part of selective configuration.
2.Security Execution flowchart
On the basis of this theoretical knowledge and code knowledge, I directly post the flow chart
3. Security Oauth2 principle
Having seen how Security works, let’s take a look at how oAuth2 works.
-
How to build Security Oauth2 on top of Security framework?
-
What has changed with Security Oauth2?
-
How are the four authentication methods of Oauth2 implemented?
With these questions in mind, let’s go back to the component realization to execution flowchart
The component of cognitive
TokenEndpoint:
Understood as a Controller, the /oauth/token interface is here. When we say Controller, that’s where the business logic is handled, that’s where the Oauth logic is handled.
TokenGranter:
Component level means token issuer, and the implementation of the Oauth2 specification is implemented by this component
TokenServices :
Defines some operations on tokens, such as creating, obtaining, and refreshing. We understand it as the Sevevice layer.
- Use the tokenSerrvices AuthorizationServerTokenServices: authorization server
- Server-side tokenservices ResourceServerTokenServices: resources
Thus the relationship architecture of the three components comes out:
The request goes to the Controller and is handed to TokenGranter for authorization. TokenGranter invokes TokenServices to generate tokens during authorization.
Code-level cognition:
Integrating oAuth2 gives us two more configuration classes, why??
// Permission server configuration
@Configuration
@EnableAuthorizationServer
protected static class MyAuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
}
/ / @ EnableAuthorizationServer annotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({AuthorizationServerEndpointsConfiguration.class, AuthorizationServerSecurityConfiguration.class})
public @interface EnableAuthorizationServer {
}
// Resource server configuration
@Configuration
@EnableResourceServer
protected static class MyResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
}
/ / @ EnableResourceServer annotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ResourceServerConfiguration.class)
public @interface EnableResourceServer {
}
Copy the code
Permission server configuration:
@ EnableAuthorizationServer comments: this annotation is active two main configuration class
- TokenEndpoint AuthorizationServerEndpointsConfiguration: configuration such as the Controller class, which is registered Bean Controller type, such as/request/token interface
- AuthorizationServerSecurityConfiguration: indirect SecurityConfigurer interface is realized. As mentioned above, the SecurityConfigurer interface is collected and parsed by the WebSecurityConfiguration class when Security is enabled. Thus the Oauth2 configuration is associated with the Security configuration architecture.
MyAuthorizationServerConfiguration: inheritance in AuthorizationServerConfigurerAdapter, indirect inherited AuthorizationServerConfigurer. See AuthorizationServerConfigurer, as you can imagine there should be a xxxConfiguration configuration file to parse. Yes, he is * * * * AuthorizationServerSecurityConfiguration collecting parsing. And AuthorizationServerSecurityConfiguration would be WebSecurityConfiguration configuration class to collect. This way our custom configuration is associated with the Security configuration architecture
public class AuthorizationServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private List<AuthorizationServerConfigurer> configurers = Collections.emptyList();
}
Copy the code
Resource server configuration:
EnableResourceServer comments: mainly activated ResourceServerConfiguration class
- ResourceServerConfiguration: also indirectly realized SecurityConfigurer interface, that is to say, will also be WebSecurityConfiguration configuration class to collect parsing.
MyResourceServerConfiguration: custom configurations. Implements ResourceServerConfigurer interface, he would be ResourceServerConfiguration configuration class to collect parsing, and will eventually enter WebSecurityConfiguration configuration class
It can be seen that when Oauth2 is integrated, the seemingly extra two configuration classes are actually indirectly configuring Security, which will eventually take effect within the Security framework. It also shows that the Oauth2 framework is built on the Security framework.
4.Security Oauth2 Flow chart
Token Acquisition Flowchart
Interface Request Flowchart
5. To summarize
- Spring Security is filter-based in web applications
- Spring Security Oauth2 adds authentication mode logic based on the Security framework
If there are any mistakes in this article, please comment, appreciate! If the article which points do not understand, you can contact me to exchange learning!
Wechat public number: source action to learn source code, action, to source action