09.Cross Origin Resource Sharing (CORS) - JohnyzHub/jax-rs GitHub Wiki
Cross-Origin Resource Sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from a different domain than the one serving the web page. It enables web applications to make requests to resources located outside their own domain, which is not normally allowed due to security restrictions implemented by web browsers.
Origin: The origin is defined as the protocol (http/https), hostname, and port of the web application.
Requested Resource: The resource being requested on a different domain.
Browser Security Model: Browsers enforce the same-origin policy to prevent unauthorized access to resources from other domains.
CORS is important for several reasons:
Enabling Single Page Applications (SPAs): Allows SPAs to make requests to backend services hosted on different domains.
API Integration: Enables web applications to consume APIs from third-party services.
Microservices Architecture: Facilitates communication between microservices hosted on different domains.
The CORS process involves two main steps:
Preflight Request: An OPTIONS request is sent by the browser before sending the actual request.
Actual Request: If the preflight request is successful, the browser sends the original request.
Spring Boot provides built-in support for configuring CORS through Java configuration or annotations.
You can use the @CrossOrigin annotation at the controller level or method level:
@RestController
public class MyController {
@GetMapping("/api/data")
@CrossOrigin(origins = "http://example.com")
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Data");
}
}
This allows cross-origin requests only from http://example.com/
For more fine-grained control, you can configure CORS globally:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true);
}
}
This configuration allows cross-origin requests on all endpoints starting with /api/, from http://example.com/, for GET, POST, PUT, and DELETE methods.
Be specific about allowed origins, methods, and headers.
Use HTTPS for production environments.
Implement proper security measures, such as CSRF protection.
Consider using Spring Security for more advanced CORS requirements.
To test your CORS configuration, use a tool like Postman or cURL to send requests from different origins. Inspect network requests in browser developer tools to check response headers.
Example using curl:
curl -X GET \
http://localhost:8080/api/data \
-H 'Origin: http://example.com' \
-H 'Access-Control-Request-Method: GET'
Preflight Requests: Solution: Ensure your server handles OPTIONS requests correctly.
Credentials: Solution: Set allowCredentials(true) in your CORS configuration.
Non-Allowed Methods: Solution: Specify allowed methods in your CORS configuration.
Browser Cache: Solution: Clear browser cache or use cache-busting techniques.
By properly implementing CORS in your Spring Boot application, you can create secure and flexible RESTful services that work seamlessly across different domains and browsers.