You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Postman Interceptor从Spring Boot(Spring Security)捕获CSRF/XSRF令牌

Let's break down your problem step by step and fix each part—since you're working with the newer Spring Security setup (no more WebSecurityConfigurerAdapter) and Postman Interceptor, there are a few key tweaks needed to get the CSRF token flow working with Basic Authentication.

Spring Security Configuration Fixes

First, let's make sure your SecurityConfig is properly set up for both Basic Auth and CSRF with cookie-based tokens. Here's a complete, working example using the current SecurityFilterChain approach:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // Enable Basic Authentication
            .httpBasic(httpBasic -> {})
            // Configure CSRF with cookie tokens accessible to Postman/JS
            .csrf(csrf -> csrf
                .csrfTokenRepository(customCsrfTokenRepository())
            )
            // Allow unauthenticated access to a "safe" endpoint to fetch CSRF token
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/health").permitAll()
                .anyRequest().authenticated()
            );

        return http.build();
    }

    private CookieCsrfTokenRepository customCsrfTokenRepository() {
        CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
        // Fix SameSite issue for Chrome 109+ and Postman Interceptor
        // For localhost HTTP, use Lax (None requires HTTPS)
        repository.setCookieSameSite("Lax");
        // If using HTTPS locally, uncomment these lines:
        // repository.setCookieSecure(true);
        // repository.setCookieSameSite("None");
        return repository;
    }
}

Key details here:

  • We explicitly enable Basic Auth with .httpBasic()
  • A public endpoint like /api/health lets you fetch the CSRF token without needing auth first
  • The customCsrfTokenRepository() adjusts the SameSite cookie attribute to bypass Chrome's restrictions (since you can't modify flags in v109+)
Postman Interceptor & CSRF Token Flow Fixes

Now let's get Postman set up correctly to capture and use the CSRF token:

  1. Enable Postman Interceptor

    • Click the Interceptor icon (satellite dish) in Postman's top-right corner and toggle it on. Ensure "Capture cookies" is checked.
  2. Fetch the CSRF Token First

    • Create a GET request to your public endpoint (e.g., GET http://localhost:8080/api/health). Send this request—it will set the XSRF-TOKEN cookie in Postman.
  3. Fix the Test Script

    • Go to the "Tests" tab of this GET request and use this corrected script:
      // Retrieve the XSRF-TOKEN cookie
      const xsrfToken = pm.cookies.get("XSRF-TOKEN");
      if (xsrfToken) {
          // Decode the URL-encoded token and save to environment variable
          pm.environment.set("xsrf-token", decodeURIComponent(xsrfToken));
          console.log("XSRF token saved:", xsrfToken);
      } else {
          console.error("Failed to find XSRF-TOKEN cookie");
      }
      
  4. Configure Authenticated Requests

    • For POST/PUT/DELETE requests (the ones requiring CSRF protection):
      • Go to the "Auth" tab, select "Basic Auth", and enter your username/password.
      • Add a header in the "Headers" tab:
        • Key: X-XSRF-TOKEN (note the full name—you had X-XSRF before, which is incorrect)
        • Value: {{xsrf-token}} (pulls the token from your environment variable)
SSL Certificate Setup (If Using HTTPS)

If your Spring Boot app runs over HTTPS locally, fix the certificate trust issue like this:

  1. Export Postman's CA Certificate

    • In Postman, go to Settings > Certificates > CA Certificates
    • Click "Download CA Certificate" and save the file (e.g., postman-ca.crt)
  2. Import to Chrome

    • Open Chrome, go to Settings > Privacy and security > Security > Manage certificates
    • Navigate to the "Trusted Root Certification Authorities" tab, click "Import"
    • Select the postman-ca.crt file and follow prompts to add it to trusted roots
Additional Troubleshooting Tips
  • Check Cookie Presence: After sending the GET request, verify XSRF-TOKEN exists in Postman's "Cookies" tab under the request.
  • Request Method Rules: Spring Security only requires CSRF tokens for "unsafe" methods (POST, PUT, DELETE, PATCH)—GET requests don't need the token.
  • Environment Selection: Ensure you've selected the correct Postman environment where xsrf-token is stored.

内容的提问来源于stack exchange,提问作者Ola Lindgard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:10:28