如何用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.
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/healthlets 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+)
Now let's get Postman set up correctly to capture and use the CSRF token:
Enable Postman Interceptor
- Click the Interceptor icon (satellite dish) in Postman's top-right corner and toggle it on. Ensure "Capture cookies" is checked.
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 theXSRF-TOKENcookie in Postman.
- Create a GET request to your public endpoint (e.g.,
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"); }
- Go to the "Tests" tab of this GET request and use this corrected script:
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 hadX-XSRFbefore, which is incorrect) - Value:
{{xsrf-token}}(pulls the token from your environment variable)
- Key:
- For POST/PUT/DELETE requests (the ones requiring CSRF protection):
If your Spring Boot app runs over HTTPS locally, fix the certificate trust issue like this:
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)
- In Postman, go to
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.crtfile and follow prompts to add it to trusted roots
- Open Chrome, go to
- Check Cookie Presence: After sending the GET request, verify
XSRF-TOKENexists 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-tokenis stored.
内容的提问来源于stack exchange,提问作者Ola Lindgard

