Spring Boot - Invalid CSRF Token error for simultaneous request from Angular pages using...

Discussão em 'Angular' iniciado por Bhushan Kawadkar, Março 10, 2025.

  1. I have Spring Boot application with below CSRF code in httpFilterChain method

    public SecurityFilterChain httpFilterChain (
    HttpSecurity http,
    UserDetailsService userService,
    AuthenticationManager authManager,
    BearerTokenResolver bearerTokenResolver,
    TokenService tokenService) throws Exception
    {
    CookieCsrfTokenRepository tokenrepo =
    CookieCsrfTokenRepository.withHttpOnlyFalse();

    tokenrepo.setCookieCustomizer(c -> {
    c.maxAge(30 * 60);
    c.path("/");
    c.sameSite("Strict");
    });

    CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
    requestHandler.setCsrfRequestAttributeName(null);

    http = http
    .x509(x509 -> configureX509(x509, authManager, bearerTokenResolver, tokenService))

    .sessionManagement((session) -> session
    .sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
    .logout(logout -> {
    logout.invalidateHttpSession(true);
    logout.clearAuthentication(true);
    logout.logoutUrl("/api/logout");
    logout.logoutSuccessUrl("/logon");
    })
    .authorizeHttpRequests(auth -> auth
    .requestMatchers(matchers(AUTH_WHITELIST)).permitAll()
    .requestMatchers(matchers(AUTHENTICATED_ENDPOINTS)).authenticated())

    .csrf(csrf -> csrf
    .csrfTokenRepository(tokenrepo)
    .csrfTokenRequestHandler(requestHandler))
    .headers( h -> h
    .httpStrictTransportSecurity( c -> {
    c.maxAgeInSeconds(31536000);
    c.includeSubDomains(true);
    c.preload(false);
    }).addHeaderWriter(new StaticHeadersWriter(CONTENT_SECURITY_POLICY, CSP_PARAMS)));


    return http.build();
    }

    While calling few GET and PUT methods in Angular 18 page, I am using 'X-XSRF-TOKEN in header and cookies, which works well in chrome but it fails sometimes in Firefox browser.

    Sample - Network request
    `PUT /api/servers/bhushan HTTP/1.1
    Host: xxx-xxx-xxx.xx.com
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0
    Accept: application/json, text/plain, */*
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate, br, zstd
    Content-Security-Policy: default-src 'none'; img-src 'self'; form-action 'self';style-src 'self'
    Authorization: Bearer eyJ4NXQjUzI1NiI6IkhuVnRxRGJMcHFva3Jwc3ViY2JaTDY1U1Eyc25IdWtkaG1qMVF0WVRpN0EiLCJraWQiOiJtdmNtIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJoYWltIiwidW5pcXVlLWtleSI6Ii9EWktqZitkeWg1ekdUTHlURm9tcTk5UVByUjRKWTBjU0l4N2J6UlF2Z3FyanVEdjBmT3B6S3JBODVFUTlVVjVnS0Y4YkRmRU0rSzZvdFNveHpZc0NqQmtFU20zZW1VTGZ5TzdaNTM3aGxCNm9Na3lZejlVSE1HclZwSGxrNjNHandhUlJ1bWdFL1BiZmx2TWxUUWJiWUxtVjExSlZIRmt4RFZnR29vUDBRMD0iLCJ0aWNrZXQiOiIwajdqUVJpNE9mMzRNSHNVbEFBaElnSW1oREJmRElJZUFtRmNPZVZuNmlrQUlML0tabGwyZjZzOFJMN1FZOE1CN0g1QlQ2eFVWeUdMYzlqcm5TWGciLCJzY29wZSI6IjMgNCAxIDIgNSIsImlzcyI6InNlbGYiLCJleHAiOjE3NDE1OTcxNzYsImlhdCI6MTc0MTU4OTk3NiwidXNlcm5hbWUiOiJoYWltIn0.MntgvBQ3VjwnFKo597C2stw_x6aLDnCii4eH9LVlUqsEi7p3U_Y7UTUi9VtcQYf_jiDU0v20eePtfFfiuZTosFCvY756mp2cFE5wi9VSSEYKLwW5cmG5GPdnU0X5GCERUu05DtPW9jVVrzheM3oouLt5H1C-orfBaypgfAoZLjuik8Zhf_toYxc_ljortqDgTREqqqMbbW_uyImA9oBJfHOeqsSkwcX4zjiPfUNPfGJSbaAViSMKK-0Lycxv4UMC9-BpR2k0lcxZ_1nVa9tku02C4IgxoJuljrd9VySrXvYjj3Ujwn-RZDMWoxJE3Mzwm5kmhJfNUch8483n2xeETw
    X-XSRF-TOKEN: 75dc0945-8fb8-420a-b001-d4426698cd84
    Content-Type: application/json
    Content-Length: 175
    Origin: https://xxx-xxx-xxx.xx.com
    Connection: keep-alive
    Referer: https://xxx-xxx-xxx.xx.com/configurations
    Cookie: JSESSIONID=39ED72EAE938781B1914245939D2EACF; XSRF-TOKEN=75dc0945-8fb8-420a-b001-d4426698cd84; x-api-session=eyJ4NXQjUzI1NiI6IkhuVnRxRGJMcHFva3Jwc3ViY2JaTDY1U1Eyc25IdWtkaG1qMVF0WVRpN0EiLCJraWQiOiJtdmNtIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJoYWltIiwidW5pcXVlLWtleSI6Ii9EWktqZitkeWg1ekdUTHlURm9tcTk5UVByUjRKWTBjU0l4N2J6UlF2Z3FyanVEdjBmT3B6S3JBODVFUTlVVjVnS0Y4YkRmRU0rSzZvdFNveHpZc0NqQmtFU20zZW1VTGZ5TzdaNTM3aGxCNm9Na3lZejlVSE1HclZwSGxrNjNHandhUlJ1bWdFL1BiZmx2TWxUUWJiWUxtVjExSlZIRmt4RFZnR29vUDBRMD0iLCJ0aWNrZXQiOiIwajdqUVJpNE9mMzRNSHNVbEFBaElnSW1oREJmRElJZUFtRmNPZVZuNmlrQUlML0tabGwyZjZzOFJMN1FZOE1CN0g1QlQ2eFVWeUdMYzlqcm5TWGciLCJzY29wZSI6IjMgNCAxIDIgNSIsImlzcyI6InNlbGYiLCJleHAiOjE3NDE1OTcxNzYsImlhdCI6MTc0MTU4OTk3NiwidXNlcm5hbWUiOiJoYWltIn0.MntgvBQ3VjwnFKo597C2stw_x6aLDnCii4eH9LVlUqsEi7p3U_Y7UTUi9VtcQYf_jiDU0v20eePtfFfiuZTosFCvY756mp2cFE5wi9VSSEYKLwW5cmG5GPdnU0X5GCERUu05DtPW9jVVrzheM3oouLt5H1C-orfBaypgfAoZLjuik8Zhf_toYxc_ljortqDgTREqqqMbbW_uyImA9oBJfHOeqsSkwcX4zjiPfUNPfGJSbaAViSMKK-0Lycxv4UMC9-BpR2k0lcxZ_1nVa9tku02C4IgxoJuljrd9VySrXvYjj3Ujwn-RZDMWoxJE3Mzwm5kmhJfNUch8483n2xeETw
    Sec-Fetch-Dest: empty
    Sec-Fetch-Mode: cors
    Sec-Fetch-Site: same-origin
    Priority: u=0`



    I am not understanding why it is failing sometimes only and that too on firefox browser. I tried to debug logs but there is nothing useful found.

    Below is the logs in tomcat server -

    Invalid CSRF Token: {}Invalid CSRF Token '75dc0945-8fb8-420a-b001-d4426698cd84' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.

    I tried to change CSRF setting like below

    tokenrepo.setCookieCustomizer(c -> {
    c.maxAge(30 * 60);
    c.path("/");
    c.sameSite("Strict");
    });


    Also, tried changing session settings as below

    .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))

    Continue reading...

Compartilhe esta Página