Poking fun at Spring Security

It was really easy to use at first, just adding dependencies and a few configuration classes, but when you tried to use OAuth2 with Spring Security’s default login functionality, you didn’t know what to do. Without a general understanding of Spring Security, there is no such thing as flexibility.

The simplest configuration

Modified pom. XML

<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <! - if using OAuth2 still need additional configuration should rely on - > < the dependency > < groupId > org. Springframework. Security. Request < / groupId > < artifactId > spring ws-security - oauth2 < / artifactId > < version > 2.3.5. RELEASE < / version > < / dependency >Copy the code

Added Spring Security configuration classes

@EnableWebSecurity @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Bean @override public UserDetailsService userDetailsServiceBean() {UserDetails user = user // Configure a user whose username is user1 and password is 123456 .withusername ("user1").password(passwordEncoder().encode("123456")).roles("USER").build(); / / InMemoryUserDetailsManager demonstration design purpose is primarily to test and function return new InMemoryUserDetailsManager (user); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}Copy the code

New OAuth2 configuration class (note that Spring Security filters are executed sequentially due to @order Order, The default filter order is OAuth2 authorization -> OAuth2 Resource -> Spring Security)

@EnableAuthorizationServer @Configuration public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter { private final AuthenticationManager authenticationManager; private final PasswordEncoder passwordEncoder; public OAuth2AuthorizationConfig(AuthenticationManager authenticationManager, PasswordEncoder passwordEncoder) { this.authenticationManager = authenticationManager; this.passwordEncoder = passwordEncoder; } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { // AllowFormAuthenticationForClients only held behind tokenKeyAccess / / and checkTokenAccess, otherwise the impassability OAuth2. security.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()") .allowFormAuthenticationForClients(); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // Client.inmemory ().withClient("client1").secret(passwordEncoder. Encode ("123456")) .authorizedGrantTypes("authorization_code", "password", "refresh_token") There is no special meaning. The scopes (" ALL "). AccessTokenValiditySeconds (3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); }}Copy the code
@EnableResourceServer @Configuration public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { // !!! Http.requestmatcher ((request) -> {return request.getheader ("Authorization")! = null; }); http.authorizeRequests() .anyRequest() .authenticated(); }}Copy the code

Log in via Spring Security’s own login pagehttp://127.0.0.1:8080/login

Obtain the token through OAuth2http://127.0.0.1:8080/oauth/token?username=user1&password=123456&grant_type=password&client_id=client1&client_secret=123 456

Access resources using the obtained token

This section describes the principles of Spring Security

To implement authentication and authorization through DelegatingFilterProxy, FilterChainProxy, and SecurityFilterChain, note 1. Only the first matched SecurityFilterChain in a request will be executed. 2. A series of related to authentication/authorization in SecurityFilterChain filters, including FilterSecurityInterceptor.

Key components of Spring Security (copywww.springcloud.cc/spring-secu…)

  • SecurityContextHolder, provides several types of accessSecurityContextThe way.
  • SecurityContext, saveAuthenticationInformation and security information corresponding to the request.
  • Authentication, showing Spring Security specific principals.
  • GrantedAuthorityThe permissions you give the subject in the application scope.
  • UserDetailsThrough your application DAO, provide the necessary information to build the Authentication object.
  • UserDetailsService, create aUserDetails, pass oneStringType of user name (or certificate ID or whatever).

The SecurityContextHolder is the most fundamental object from which to retrieve the SecurityContext SecurityContext.

/ / code from https://www.springcloud.cc/spring-security-zhcn.html Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { String username = ((UserDetails)principal).getUsername(); } else { String username = principal.toString(); }Copy the code

The UserDetailsService command is used to load user information based on the user name.

public interface UserDetailsService {
   UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
Copy the code

ProviderManager is an implementation of AuthenticationManager, which validates authentication information through a series of AuthenticationProvider implementation classes.

public interface AuthenticationManager {
   Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
Copy the code

Here are some articles I have read from other authors

  • Spring Security reference manual in Chinese www.springcloud.cc/spring-secu…
  • Blog.csdn.net/weixin_4387…