Understanding CORS and CSRF in Spring Boot
1. CORS (Cross-Origin Resource Sharing)
Definition:
CORS is a security feature implemented in browsers that controls how web applications access resources from a different domain. It is designed to prevent a web page from making requests to a domain other than the one that served the page. This is particularly important for APIs, where clients (like web applications) hosted on different domains may need to access your Spring Boot server.
How CORS Works:
- When a browser makes a cross-origin request (e.g., your front-end on
http://localhost:3000making a request to your Spring Boot API running onhttp://localhost:8080), it sends a pre-flight request (anOPTIONSrequest) to the server to check if the server allows such a cross-origin request. - The server responds with a set of headers that indicate whether the actual request is permitted.
Configuring CORS in Spring Boot:
You can configure CORS globally or on specific controllers.
Example — Global CORS Configuration in Spring Boot:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // Allow CORS on all paths
.allowedOrigins("http://localhost:3000") // Allow specific origin
.allowedMethods("GET", "POST", "PUT", "DELETE") // Allow specific methods
.allowedHeaders("*") // Allow all headers
.allowCredentials(true); // Allow credentials (e.g., cookies)
}
}2. CSRF (Cross-Site Request Forgery)
Definition:
CSRF is a type of attack in which a malicious website tricks a user’s browser into performing an unwanted action on a different website where the user is authenticated (e.g., submitting a form, making a transaction). It exploits the trust that a website has in the user’s browser.
How CSRF Works:
- If a user is logged into a website (e.g., a banking site), an attacker can create a malicious page that tricks the user’s browser into sending requests to that site without the user’s consent. This can result in unauthorized actions, such as money transfers or account changes.
- CSRF protection ensures that the requests sent to the server come from a legitimate source by requiring a token (CSRF token) to be included in forms or headers.
CSRF Protection in Spring Boot:
By default, Spring Security provides CSRF protection. When CSRF protection is enabled, each form submission includes a CSRF token that is validated by the server.
- CSRF token is a unique, secret, and unpredictable value that is generated by the server and included in HTTP requests (usually in forms or headers). The server checks this token to ensure that the request is legitimate.
Disabling CSRF:
In cases where you’re working with stateless APIs (e.g., using JWT tokens for authentication), you might want to disable CSRF since it is not relevant for stateless services.
Example — Disabling CSRF in Spring Boot:
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // Disable CSRF protection
.authorizeRequests()
.anyRequest().authenticated(); // Ensure all requests are authenticated
}
}- CORS: A browser-based security feature that controls cross-origin requests from web applications. It is configured using headers, and Spring Boot allows flexible configuration.
- CSRF: A security mechanism to protect against malicious requests (like form submissions) that could trick a user into performing unwanted actions on a site they are authenticated on. Spring Security has CSRF protection enabled by default but can be disabled for stateless APIs.





