Java-29290 :- Upgrade spring-security-core-2 to use Spring Boot 3 (#15491)

* Made changes to upgrade to Spring Boot 3 from Boot 2

* JAVA-29290 :- Changed to use @Import for initializing the config.

* JAVA-29290 :- Made changes to use authorizeHttpRequests as authorizeRequests is deprecated

* Minor formatting fixes

* JAVA-29290 : Formatting changes
This commit is contained in:
Amit Pandey 2024-01-06 21:42:08 +05:30 committed by GitHub
parent 0a18e140e3
commit 3253f44784
18 changed files with 137 additions and 145 deletions

View File

@ -10,12 +10,13 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<properties>
<spring.security.version>5.8.4</spring.security.version>
<start-class>com.baeldung.authresolver.AuthResolverApplication</start-class>
</properties>
<dependencies>
@ -55,12 +56,10 @@
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.security.version}</version>
</dependency>
</dependencies>

View File

@ -1,7 +1,8 @@
package com.baeldung.authresolver;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;

View File

@ -1,11 +1,11 @@
package com.baeldung.dsl;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import java.util.List;
public class ClientErrorLoggingConfigurer extends AbstractHttpConfigurer<ClientErrorLoggingConfigurer, HttpSecurity> {
@ -26,7 +26,7 @@ public class ClientErrorLoggingConfigurer extends AbstractHttpConfigurer<ClientE
@Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new ClientErrorLoggingFilter(errorCodes), FilterSecurityInterceptor.class);
http.addFilterAfter(new ClientErrorLoggingFilter(errorCodes), AuthorizationFilter.class);
}
}

View File

@ -1,14 +1,10 @@
package com.baeldung.dsl;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
@ -16,6 +12,9 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import java.io.IOException;
import java.util.List;
public class ClientErrorLoggingFilter extends GenericFilterBean {
private static final Logger logger = LogManager.getLogger(ClientErrorLoggingFilter.class);

View File

@ -2,6 +2,7 @@ package com.baeldung.dsl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
@ -15,14 +16,12 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin*")
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin*")
.hasAnyRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.authenticated())
.formLogin(Customizer.withDefaults())
.apply(clientErrorLogging());
return http.build();
}

View File

@ -1,13 +1,12 @@
package com.baeldung.exceptionhandler.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import java.io.IOException;
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override

View File

@ -1,13 +1,12 @@
package com.baeldung.exceptionhandler.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import java.io.IOException;
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override

View File

@ -1,17 +1,16 @@
package com.baeldung.exceptionhandler.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import java.io.IOException;
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override

View File

@ -1,8 +1,10 @@
package com.baeldung.exceptionhandler.security;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -41,30 +43,23 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.httpBasic()
.disable()
.authorizeRequests()
.antMatchers("/login")
.permitAll()
.antMatchers("/customError")
.permitAll()
.antMatchers("/access-denied")
.permitAll()
.antMatchers("/secured")
.hasRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin()
.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler())
.and()
.logout();
http.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login")
.permitAll()
.requestMatchers("/customError")
.permitAll()
.requestMatchers("/access-denied")
.permitAll()
.requestMatchers("/secured")
.hasRole("ADMIN")
.anyRequest()
.authenticated())
.formLogin(form -> form.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler()))
.exceptionHandling(ex -> ex.accessDeniedHandler(accessDeniedHandler()))
.logout(Customizer.withDefaults());
return http.build();
}

View File

@ -3,10 +3,9 @@ package com.baeldung.global.exceptionhandler.security;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;

View File

@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
@ -34,17 +35,13 @@ public class CustomSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login")
.and()
.authorizeRequests()
.anyRequest()
.hasRole("ADMIN")
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(authEntryPoint);
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/login")
.authenticated()
.anyRequest()
.hasRole("ADMIN"))
.httpBasic(basic -> basic.authenticationEntryPoint(authEntryPoint))
.exceptionHandling(Customizer.withDefaults());
return http.build();
}

View File

@ -1,11 +1,8 @@
package com.baeldung.global.exceptionhandler.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.AuthenticationException;
@ -13,6 +10,8 @@ import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.io.IOException;
@Component("delegatedAuthenticationEntryPoint")
public class DelegatedAuthenticationEntryPoint implements AuthenticationEntryPoint {

View File

@ -5,6 +5,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
@ -24,17 +25,11 @@ public class DelegatedSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login-handler")
.and()
.authorizeRequests()
.anyRequest()
.hasRole("ADMIN")
.and()
.httpBasic()
.and()
.exceptionHandling()
.authenticationEntryPoint(authEntryPoint);
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/login-handler")
.hasRole("ADMIN"))
.httpBasic(basic -> basic.authenticationEntryPoint(authEntryPoint))
.exceptionHandling(Customizer.withDefaults());
return http.build();
}

View File

@ -2,8 +2,10 @@ package com.baeldung.httpsecurityvswebsecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@ -13,18 +15,12 @@ public class HttpSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// Given: HttpSecurity configured
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin(form -> form.loginPage("/login").permitAll())
.logout(LogoutConfigurer::permitAll);
// When: Accessing specific URLs
// Then: Access is granted based on defined rules

View File

@ -26,7 +26,7 @@ public class SecurityConfiguration {
@Bean
public HttpFirewall allowHttpMethod() {
List<String> allowedMethods = new ArrayList<String>();
List<String> allowedMethods = new ArrayList<>();
allowedMethods.add("GET");
allowedMethods.add("POST");
StrictHttpFirewall firewall = new StrictHttpFirewall();
@ -41,7 +41,7 @@ public class SecurityConfiguration {
@Bean
public WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().antMatchers("/resources/**", "/static/**");
return (web) -> web.ignoring().requestMatchers("/resources/**", "/static/**");
}
@Bean
@ -65,13 +65,14 @@ public class SecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**")
.hasRole("ADMIN")
.anyRequest()
.permitAll())
.httpBasic(withDefaults())
.formLogin(withDefaults())
.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/admin/**")
.hasRole("ADMIN")
.anyRequest()
.permitAll())
.httpBasic(withDefaults())
.formLogin(withDefaults())
.csrf(AbstractHttpConfigurer::disable);
return http.build();
}

View File

@ -2,6 +2,7 @@ package com.baeldung.httpsecurityvswebsecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.beans.factory.annotation.Autowired;
@ -14,35 +15,37 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class WebSecurityConfig {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService);
AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(
AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService);
AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
http.setSharedObject(AuthenticationManager.class, authenticationManager);
http.authorizeRequests()
.antMatchers("/")
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin().and()
.authenticationManager(authenticationManager)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
.authenticated())
.formLogin(Customizer.withDefaults())
.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
return http.build();
}
protected void configure(HttpSecurity http) throws Exception {
protected void configure(HttpSecurity http) throws Exception {
}
}
}

View File

@ -2,9 +2,11 @@ package com.baeldung.xss;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
@Configuration
public class SecurityConf {
@ -13,15 +15,17 @@ public class SecurityConf {
public WebSecurityCustomizer webSecurityCustomizer() {
// Ignoring here is only for this example. Normally people would apply their own authentication/authorization policies
return (web) -> web.ignoring()
.antMatchers("/**");
.requestMatchers("/**");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers()
.xssProtection()
.and()
.contentSecurityPolicy("script-src 'self'");
http.headers(headers ->
headers.xssProtection(
xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK)
).contentSecurityPolicy(
cps -> cps.policyDirectives("script-src 'self'")
));
return http.build();
}
}

View File

@ -5,10 +5,17 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.baeldung.exceptionhandler.security.CustomAccessDeniedHandler;
import com.baeldung.exceptionhandler.security.CustomAuthenticationFailureHandler;
import com.baeldung.global.exceptionhandler.controller.LoginController;
import com.baeldung.global.exceptionhandler.security.CustomAuthenticationEntryPoint;
import com.baeldung.global.exceptionhandler.security.DelegatedAuthenticationEntryPoint;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@ -17,6 +24,7 @@ import com.baeldung.exceptionhandler.security.SecurityConfig;
@RunWith(SpringRunner.class)
@WebMvcTest(SecurityConfig.class)
@Import(SecurityConfig.class)
class SecurityConfigUnitTest {
@Autowired
private MockMvc mvc;