Spring Security 6 with Spring Boot 3
Say goodbye to Old security , Say Hi to Spring Security 6 with Spring Boot 3 . it is easier and simpler.
Spring Security is a powerful and highly customizable authentication and access-control framework. it focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements.
Spring Boot provides a spring-boot-starter-security starter that aggregates Spring Security-related dependencies. you can manually add the starter, as the following example shows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
When we add the spring security dependency, spring security enables the security filter chain. These filters are responsible for Spring Security. So any incoming request will go through these filters and it is here that authentication and authorization takes place.
When the username and password are submitted, the UsernamePasswordAuthenticationFilter authenticates the username and password. The UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, so the following diagram should look pretty similar:
The magic starts Here !
All in one security config . handling cors , csrf , session managment , permitted/Authorized HttpMethods/URLs .
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
JwtAuthFilter jwtAuthFilter,
OAuthLoginSuccessHandler oAuthLoginSuccessHandler)
throws Exception {
http
//how to handle anonymous users
.anonymous(AbstractHttpConfigurer::disable)
//cors filter to be user
.cors(c -> c.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.POST ,"/permitted/**" ).permitAll())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.GET ,"/v3/api-docs/**","/swagger-ui/**","/actuator/**" ).permitAll())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.POST,"/**" ).authenticated())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.GET,"/**" ).authenticated())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.DELETE,"/**" ).authenticated())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.PUT,"/**" ).authenticated())
.authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.PATCH,"/**" ).authenticated())
//any custom filter needs to injected in the chain
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
//handling exception globally
.exceptionHandling(httpSecurityExceptionHandlingConfigurer ->
httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(new
HttpStatusEntryPoint(HttpStatus.FORBIDDEN)))
// Disable "JSESSIONID" cookies
.sessionManagement(conf ->
conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
For authentication provider , Multiple AuthenticationProviders are available , the example below chooses DaoAuthenticationProvider with usres in db. CustomUserDetailsService handle loadUserByUsername() that retrieves users from db to return UserDetails
领英推荐
@Bean
public UserDetailsService userDetailsService(){
return new CustomUserDetailsService();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider =
new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService());
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
Springboot oauth2login with providers like Google for example as simple as follows all is needed creating oAuthLoginSuccessHandler to handle sucess login from aourh2 provider.
.oauth2Login(httpSecurityOAuth2LoginConfigurer ->
httpSecurityOAuth2LoginConfigurer.successHandler(oAuthLoginSuccessHandler))
Don't forget to enable web secuity by adding
@EnableWebSecurity
Rest controller can further manage roles as follows :
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ResponseEntity<MyResponse> myAdminndpoint(){
.............................
}
Don't forget to add method security
@EnableMethodSecurity
Security is done!
To migrate to spring security 6 , follow https://docs.spring.io/spring-security/reference/6.0/migration/index.html