Security Configuration

Configuring Spring Security using SecurityFilterChain

Instead of using WebSecurityConfigurerAdapter (which is deprecated), use SecurityFilterChain in Spring Boot 3+.

Security Configuration Class

SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll() // Public endpoints
.requestMatchers("/admin/**").hasRole("ADMIN") // Admin only
.anyRequest().authenticated() // All other endpoints require authentication
)
.formLogin(withDefaults()) // Enable default login page
.logout(withDefaults()); // Enable logout

return http.build();
}
}
  • permitAll() → Allows access to public endpoints.
  • hasRole("ADMIN") → Restricts access to users with ADMIN role.
  • formLogin() → Enables form-based login.
  • logout() → Enables logout functionality.

Custom Login and Logout Handlers

If you need custom login/logout handling, you can define your authentication logic.

Custom Login Handling

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.formLogin(login -> login
.loginPage("/login") // Custom login page
.defaultSuccessUrl("/dashboard", true) // Redirect after successful login
.failureUrl("/login?error=true") // Redirect after login failure
.permitAll()
)
.logout(logout -> logout
.logoutUrl("/perform_logout") // Custom logout URL
.logoutSuccessUrl("/login?logout=true") // Redirect after logout
.invalidateHttpSession(true) // Invalidate session
.deleteCookies("JSESSIONID") // Delete session cookie
);

return http.build();
}

Session Management & Concurrency Control

You can control user session behavior like max sessions per user and session invalidation.

SecurityConfig.java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // Create session only if required
.maximumSessions(1) // Allow only one active session per user
.expiredUrl("/session-expired") // Redirect if session expires
);

return http.build();
}


CSRF Protection (csrf().disable() vs. csrfTokenRepository())

CSRF (Cross-Site Request Forgery) protection is enabled by default in Spring Security.

Disable CSRF (Only for APIs)

Disabling CSRF is recommended only for REST APIs (stateless applications).

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()); // Disables CSRF (Not recommended for web apps)

return http.build();
}

Enable CSRF with Token Repository

For form-based applications, use CsrfTokenRepository:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // Store CSRF token in a cookie
);

return http.build();
}

CORS Configuration with Security

If your frontend (React/Angular/Vue) is hosted on a different domain, enable CORS.

Basic CORS Configuration

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(withDefaults()) // Enable CORS
.csrf(csrf -> csrf.disable()); // Disable CSRF for APIs

return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000")); // Allowed frontend URLs
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.