javaspringspring-securitysecurity-filter

Configure Spring Security Filter Chain


Good evening, I need help configuring Spring Security Chain Filter:

@Bean
    SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers("/**").permitAll()
                .anyRequest().hasAuthority("ROLE_USER")
                .and()
                .csrf().disable();

        return http.build();
    }

This is my code but it doesn't work well. What I want is:

  1. All EndPoints that do not have @PreAuthorize annotation to be free to use by anyone and everywhere.

  2. All Endpoints that have @PreAuthorize annotation require accessToken to be attached.

Also, but this is less important, IntelliJ keeps telling me that csrf is deprecated but I don't know what to use in its place.

Finally, I'd like to not disable csrf, but if I don't I cannot call my EndPoints from Postman and (likely) my frontend !

Can you help please ? Full code of the bean if possible.

If needed I can provide full class and also JWT classes.


Solution

  • @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().permitAll() // Allow all by default
            )
            .csrf(csrf -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // For frontend compatibility
                .ignoringRequestMatchers("/api/**") // Disable CSRF for API endpoints if needed
            );
        
        // Enable method security for @PreAuthorize annotations
        return http.build();
    }
    
    @Bean
    @Configuration
    @EnableMethodSecurity(prePostEnabled = true)
    public static class MethodSecurityConfig {
        // Method security configuration
    }
    
    
    }
    

    Key Improvements:
    Method Security: Added @EnableMethodSecurity to activate @PreAuthorize annotations

    Default Permissions: All endpoints are permitted by default

    CSRF Handling:

    Updated to non-deprecated syntax

    Configured Cookie-based CSRF tokens for frontend compatibility

    Option to disable for API endpoints if needed

    Important Notes:
    For @PreAuthorize to work, you need:

    The @EnableMethodSecurity annotation (as shown above)

    Proper security configuration (like JWT or OAuth2 for token validation)

    CSRF Recommendations:

    For REST APIs: It's common to disable CSRF (but use other protections like CORS)

    For traditional web apps: Keep CSRF enabled with proper token handling

    The deprecation warning is just about the method signature - use the lambda style as shown

    Postman Testing:

    If you keep CSRF enabled, you'll need to:

    First GET a CSRF token

    Include it in subsequent requests (typically as a header X-XSRF-TOKEN)

    Alternative CSRF Configuration
    If you're building a stateless API (common with JWT), you can disable CSRF completely:

    .csrf(csrf -> csrf.disable())