In the Spring framework, to prevent Cross-Site Request Forgery (CSRF), CSRF protection is typically applied to sensitive operations. When sending requests from the frontend or testing tools like Postman, ensure that the correct CSRF token is included. The following steps outline how to send Spring CSRF tokens using Postman:
Step 1: Configure Spring Security
First, ensure that Spring Security is configured with CSRF protection. This is typically set in the Spring Security configuration class:
java@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); // Other configurations... } }
Step 2: Obtain the CSRF Token
Before sending requests that require CSRF protection, you must first obtain the CSRF token. Typically, when you access a page in the application, Spring sets a CSRF token in a cookie, or it may be present as a hidden field in the page's form.
Obtain via Cookie
- Use Postman to access a page protected by Spring Security, such as the login page.
- Inspect the response cookies to find the CSRF token (typically named
XSRF-TOKEN).
Obtain via Hidden Field
- In a browser environment, inspect the page source to find a tag similar to
<input type="hidden" name="_csrf" value="xxxx">.
Step 3: Include the CSRF Token in Requests
After obtaining the CSRF token, include it in requests for operations such as POST, PUT, and DELETE.
- Set the request type to POST (or other methods requiring CSRF protection) in Postman.
- Add the CSRF token to the Headers:
- Key:
X-XSRF-TOKEN(the header name may differ based on your Spring Security configuration) - Value: [the CSRF token value obtained from the cookie or hidden field]
- Key:
Step 4: Send the Request
After configuring all necessary parameters and header information, send the request to the server. If the CSRF token is correct, your request should be accepted and processed by the server.
Example
Assume you obtained the CSRF token 12345abcde from the login page and need to send a POST request to the server:
- URL:
http://example.com/api/data - Method: POST
- Headers:
Content-Type:application/jsonX-XSRF-TOKEN:12345abcde
- Body:
json
{ "data": "value" }
With this setup, your POST request should successfully pass through Spring Security's CSRF check.
By following this approach, you can test APIs protected by CSRF in Postman, ensuring they work correctly in production environments.