Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle CSRF protection with Spring RESTful web services?

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?

like image 320
venu Avatar asked Oct 14 '15 12:10

venu


People also ask

How do I enable CSRF in Spring boot REST API?

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.

How do you prevent CSRF attacks in Spring?

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.

Do REST API need CSRF protection?

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.


1 Answers

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();
}
like image 105
holmis83 Avatar answered Sep 26 '22 02:09

holmis83