I have a Spring web application with CSRF protection enabled. I am able to access the RESTful service via AJAX calls, but when I am accessing the service with other applications like httpurlconnection, I get a 401 error (CSRF token null).
I understand that to access the RESTful service I need to pass a token in the request header, but how can I get the CSRF token?
Enable CSRF Protection With REST API If our project requires CSRF protection, we can send the CSRF token with a cookie by using CookieCsrfTokenRepository in a custom WebSecurityConfigurerAdapter. After restarting the app, our requests receive HTTP errors, which means that CSRF protection is enabled.
To protect MVC applications, Spring adds a CSRF token to each generated view. This token must be submitted to the server on every HTTP request that modifies state (PATCH, POST, PUT and DELETE — not GET). This protects our application against CSRF attacks since an attacker can't get this token from their own page.
The CSRF token is required for any later REST API calls. The client must send a valid token with every API request. The token is sent in a custom request HTTP header.
You can create a mapping in Spring MVC that gets the CSRF token:
@RequestMapping(value="/csrf-token", method=RequestMethod.GET)
public @ResponseBody String getCsrfToken(HttpServletRequest request) {
CsrfToken token = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
return token.getToken();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With