What is CORS in Spring Boot?
CORS stands for:
Cross-Origin Resource Sharing
CORS is a security mechanism used by browsers to control how web applications access resources from different domains, ports, or origins.
In Spring Boot, CORS configuration allows or restricts frontend applications from calling backend APIs hosted on different origins.
In simple words, CORS decides:
βWhich frontend applications are allowed to access backend APIs?β
What is an Origin?
An origin is a combination of:
- Protocol
- Domain
- Port
Example Origins
| URL | Origin |
|---|---|
| http://localhost:3000 | Different Origin |
| http://localhost:8080 | Different Origin |
| https://example.com | Different Origin |
Why CORS is Needed
Modern applications usually have:
- Frontend running on one server
- Backend APIs running on another server
Example:
- React App β http://localhost:3000
- Spring Boot API β http://localhost:8080
Since origins are different, browsers block requests by default for security reasons.
Real-Time Example
Suppose:
- Frontend:
http://localhost:3000 - Backend:
http://localhost:8080
React application tries to call:
http://localhost:8080/api/users
Browser blocks request unless backend explicitly allows it using CORS.
What Happens Without CORS?
Browser error example:
Access to fetch at
'http://localhost:8080/api/users'
from origin 'http://localhost:3000'
has been blocked by CORS policy
Why Browsers Enforce CORS
Browsers enforce Same-Origin Policy to prevent malicious websites from accessing sensitive user data.
Without CORS restrictions:
- Malicious websites could access APIs
- User data may leak
- Security vulnerabilities increase
How CORS Works
CORS flow:
- Frontend sends request to backend
- Browser checks origin
- Backend sends CORS headers
- Browser validates headers
- Request is allowed or blocked
Important CORS Headers
| Header | Purpose |
|---|---|
| Access-Control-Allow-Origin | Allowed frontend origin |
| Access-Control-Allow-Methods | Allowed HTTP methods |
| Access-Control-Allow-Headers | Allowed request headers |
| Access-Control-Allow-Credentials | Allow cookies/authentication |
Simple CORS Example
Access-Control-Allow-Origin:
http://localhost:3000
This means:
- Only React app running on port 3000 can access API
Enable CORS Using @CrossOrigin
Spring Boot provides:
@CrossOrigin
annotation for enabling CORS.
Controller-Level CORS Example
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {
@GetMapping
public List<String> getUsers() {
return List.of("Naresh", "Kumar");
}
}
Method-Level CORS Example
@GetMapping("/students")
@CrossOrigin(origins = "http://localhost:3000")
public List<String> getStudents() {
return List.of("Student1", "Student2");
}
Global CORS Configuration
Global configuration is recommended for enterprise applications.
Global CORS Example
@Configuration
public class CorsConfig
implements WebMvcConfigurer {
@Override
public void addCorsMappings(
CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:3000"
)
.allowedMethods(
"GET",
"POST",
"PUT",
"DELETE"
)
.allowedHeaders("*");
}
}
Explanation of Configuration
| Method | Purpose |
|---|---|
| addMapping("/**") | Applies to all APIs |
| allowedOrigins() | Allowed frontend URLs |
| allowedMethods() | Allowed HTTP methods |
| allowedHeaders() | Allowed request headers |
Allow All Origins Example
@CrossOrigin(origins = "*")
Why Allowing All Origins is Risky
Using:
*
means any website can access APIs.
This may create:
- Security risks
- Unauthorized API access
- Data exposure issues
CORS with Credentials
Sometimes frontend applications send:
- Cookies
- Authorization headers
- JWT tokens
In such cases:
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:3000"
)
.allowCredentials(true);
What is Preflight Request?
Before sending certain requests, browser sends an:
OPTIONS
request to verify CORS permissions.
Preflight Request Example
OPTIONS /api/users
Browser checks:
- Allowed methods
- Allowed headers
- Allowed origins
Simple vs Complex Requests
| Request Type | Needs Preflight |
|---|---|
| Simple GET Request | No |
| POST with JSON | Yes |
| PUT Request | Yes |
| DELETE Request | Yes |
CORS with Spring Security
When Spring Security is enabled, CORS must also be configured in SecurityFilterChain.
Spring Security CORS Example
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(csrf -> csrf.disable());
return http.build();
}
}
Why CORS is Important in Microservices
In microservices:
- Frontend and backend are usually separate
- Multiple services run on different domains
- Cross-origin communication is common
CORS enables secure communication between services and frontends.
Real-Time Example in E-Commerce Application
Suppose:
- React frontend runs on port 3000
- Spring Boot APIs run on port 8080
Frontend needs to:
- Fetch products
- Add items to cart
- Place orders
CORS configuration allows frontend to access backend APIs securely.
Advantages of CORS
- Secure cross-origin communication
- Protects APIs from unauthorized domains
- Supports frontend-backend separation
- Essential for microservices architecture
- Improves browser security
Disadvantages of Improper CORS Configuration
- Allowing all origins may expose APIs
- Incorrect setup may block frontend requests
- Complex configurations may confuse beginners
Best Practices for CORS
- Allow only trusted origins
- Avoid using "*" in production
- Restrict allowed methods
- Restrict allowed headers
- Enable credentials only when necessary
- Use HTTPS in production
Common CORS Errors
| Error | Cause |
|---|---|
| CORS policy blocked request | Origin not allowed |
| Preflight request failed | OPTIONS request blocked |
| Credentials not allowed | Missing allowCredentials(true) |
Difference Between CORS and CSRF
| Feature | CORS | CSRF |
|---|---|---|
| Purpose | Control cross-origin access | Prevent forged requests |
| Handled By | Browser | Server Security |
| Main Goal | Origin control | Request authenticity |
Common Interview Questions on CORS
What is CORS?
CORS is a browser security mechanism that controls cross-origin API access.
Why is CORS needed?
Because browsers block cross-origin requests by default for security reasons.
What is @CrossOrigin?
It is a Spring Boot annotation used to enable CORS.
What is a preflight request?
Browser sends an OPTIONS request before certain cross-origin requests.
Why should "*" be avoided in production?
Because it allows all domains to access APIs, creating security risks.
Conclusion
CORS is an important security mechanism in modern Spring Boot applications.
It enables secure communication between frontend applications and backend APIs hosted on different origins.
Proper CORS configuration is essential for React applications, Angular applications, mobile apps, microservices, and REST APIs.
Understanding CORS is critical for Spring Boot developers because frontend-backend separation is very common in modern enterprise applications.