CSRF With Stateless REST API
1. Overview
In our previous article, we've explained how CSRF attacks impact a Spring MVC application.
This article will go through different cases to determine if a stateless REST API can be vulnerable to CSRF attacks and, if so, how to protect it from them.
2. Does REST API Require CSRF Protection?
First, we can find an example of a CSRF attack in our dedicated guide.
Now, upon reading this guide, we may think that a stateless REST API wouldn't be affected by this kind of attack, as there's no session to steal on the server-side.
Let's take a typical example: a Spring REST API application and a Javascript client. The client uses a secure token as credentials (such as JSESSIONID or JWT), which the REST API issues after a user successfully signs in.
CSRF vulnerability depends on how the client stores and sends these credentials to the API.
Let's review the different options and how they will impact our application vulnerability.
We will take a typical example: a Spring REST API application and a Javascript client. The client uses a secure token as credentials (such as JSESSIONID or JWT), which the REST API issues after a user successfully signs in.
2.1. Credentials Are Not Persisted
Once we've retrieved the token from the REST API, we can set the token as a JavaScript global variable. This will save the token in the browser's memory, and it will be available only for the current page.
It's the most secure way: CSRF and XSS attacks always lead to opening the client application on a new page, which can't access the memory of the initial page used to sign in.
However, our user will have to sign in again every time he accesses or refreshes the page.
On mobile browsers, it will happen even if the browser goes background, as the system clears the memory.
This is so restricting for the user that this option is rarely implemented.
2.2. Credentials Stored in the Browser Storage
We can persist our token in the browser storage – the session storage, for example. Then, our JavaScript client can read the token from it and send an authorization header with this token in all the REST requests.
This is a prevalent way to use, for example, JWT: it's easy to implement and prevents attackers from using CSRF attacks. Indeed, unlike cookies, the browser storage variables are not sent automatically to the server.
However, this implementation is vulnerable to XSS attacks: a malicious JavaScript code can access the browser storage and send the token along with the request. In this case, we must protect our application.
2.3. Credentials Stored in Cookies
Another option is to use a cookie to persist the credentials. Then, the vulnerability of our application depends on how our application uses the cookie.
We can use a cookie to persist the credentials only, like a JWT, but not to authenticate the user.
Our JavaScript client will have to read the token and send it to the API in the authorization header.
In this case, our application is not vulnerable to CSRF: Even if the cookie is sent automatically across a malicious request, our REST API will read credentials from the authorization header and not from the cookie. However, the HTTP-only flag must be turned to false to let our client read the cookie.
However, by doing this, our application will be vulnerable to XSS attacks like in the previous section.
An alternative approach is to authenticate the requests from a session cookie, with the HTTP-only flag set to true. This is typically what Spring Security provides with the JSESSIONID cookie. Of course, to keep our API stateless, we must never use the session on the server-side.
In this case, our application is vulnerable to CSRF like a stateful application: As the cookie will be sent automatically with any REST requests, a click on a malicious link can perform authenticated operations.
2.4. Other CSRF Vulnerable Configurations
Some configurations don't use secure tokens as credentials but may also be vulnerable to CSRF attacks.
This is the case of HTTP basic authentication, HTTP digest authentication, and mTLS.
They're not very common but have the identical drawback: The browser sends credentials automatically on any HTTP requests. In these cases, we must enable CSRF protection.
3. Disable CSRF Protection in Spring Boot
Spring Security enables CSRF protection by default since version 4.
If our project doesn't require it, we can disable it in a custom WebSecurityConfigurerAdapter:
@Configuration
public class SpringBootSecurityConfiguration
extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
4. Enable CSRF Protection With REST API
4.1. Spring Configuration
If our project requires CSRF protection, we can send the CSRF token with a cookie by using CookieCsrfTokenRepository in a custom WebSecurityConfigurerAdapter.
We must set the HTTP-only flag to false to be able to retrieve it from our JavaScript client:
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
After restarting the app, our requests receive HTTP errors, which means that CSRF protection is enabled.
We can confirm that these errors are issued from the CsrfFilter class by adjusting the log level to DEBUG:
<logger name="org.springframework.security.web.csrf" level="DEBUG" />
It will display:
Invalid CSRF token found for http://...
Also, we should see in our browser that a new XSRF-TOKEN cookie is present.
Let's add a couple of lines in our REST controller to also write the information to our API logs:
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
LOGGER.info("{}={}", token.getHeaderName(), token.getToken());
4.2. Client Configuration
In the client-side application, the XSRF-TOKEN cookie is set after the first API access. We can retrieve it using a JavaScript regex:
const csrfToken = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*\=\s*([^;]*).*$)|^.*$/, '$1');
Then, we must send the token to every REST request that modifies the API state: POST, PUT, DELETE, and PATCH.
Spring is expecting to receive it in the X-XSRF-TOKEN header. We can simply set it with the JavaScript Fetch API:
fetch(url, {
method: 'POST',
body: JSON.stringify({ /* data to send */ }),
headers: { 'X-XSRF-TOKEN': csrfToken },
})
Now, we can see that our request is working, and the “Invalid CSRF token” error is gone in the REST API logs.
Therefore, it will be impossible for attackers to perform a CSRF attack. For example, a script that tries to perform the same request from a scam website will receive the “Invalid CSRF token” error.
Indeed, if the user hasn't visited the actual website first, the cookie will not be set, and the request will fail.
5. Conclusion
In this article, we reviewed the different contexts in which CSRF attacks against a REST API are possible or not.
Then, we learned how to enable or disable CSRF protection using Spring Security.
No comments:
Post a Comment