Skip to content

Instantly share code, notes, and snippets.

@Configuration
public class BasicAuthSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeHttpRequests((authorize) -> authorize.requestMatchers(new AntPathRequestMatcher("/url")).hasRole(ROLE).anyRequest().authenticated())
.httpBasic(Customizer.withDefaults()).exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
return http.build();
}
@Component
public class CustomAuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Object context=request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
//context will be null if we dont pass x-auth-token in header and null should not be set in SecurityContextHolder
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
@Configuration
@EnableMethodSecurity //- new config
//@EnableWebSecurity - old one deprecated
public class SecurityConfig { //extends WebSecurityConfigurerAdapter -
//this class WebSecurityConfigurerAdapter is now removed
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.securityContext((securityContext) -> {
spring.main.allow-bean-definition-overriding=true
spring.main.allow-circular-references=true
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
<java.version>17</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
</parent>