admin管理员组

文章数量:1123139

I am new to java we have implimented CSRF token validation for for protected routes even token matched its giving 403, please check below code. I have /api/auth/send-otp will send the otp to email address and /verify will verity the otp and if its valid return access_token and when trying to retrive refresh token with post call /token this time we are getting 403 error.


package com.example.authentication.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseCookie;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import com.example.authentication.filter.CsrfCookieFilter;

import java.util.function.Consumer;

import jakarta.servlet.http.Cookie;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf((csrf) -> csrf
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers("/api/auth/send-otp", "/api/auth/verify-otp")
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/send-otp", "/api/auth/verify-otp", "/error").permitAll()
                .requestMatchers("/api/auth/**").permitAll()
                // .requestMatchers("/api/auth/**").authenticated()
                .anyRequest().authenticated()
            )
           .cors(cors -> cors.configurationSource(corsConfigurationSource()))
           .addFilterAfter(new CsrfCookieFilter(), CsrfFilter.class); // Add custom CSRF filter
        return http.build();
    }

    

    @Bean
    public CookieCsrfTokenRepository cookieCsrfTokenRepository() {
        CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
        repository.setCookieCustomizer(cookieCustomizer());
        repository.setCookieName("XSRF-TOKEN"); // Default cookie name for CSRF token
        return repository;
    }

    private Consumer<ResponseCookie.ResponseCookieBuilder> cookieCustomizer() {
        return cookie -> {
            cookie.secure(false); // Ensure the cookie is only sent over HTTPS
            cookie.httpOnly(false); // Prevent JavaScript access to the cookie
            cookie.path("/"); // Make the cookie available application-wide
            cookie.sameSite("None");
        };
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:2345"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

本文标签: javaCSRF token validation alway giving 403 for protected routesStack Overflow