What is CORS protection and when is it needed?
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to resources on a different domain (origin).
Without CORS, the browser blocks such requests to prevent attacks like Cross-Site Request Forgery (CSRF) and other threats related to cross-origin interactions.
CORS protection is needed when:
- A web application on one domain (e.g.,
https://app.example.com) makes requests to an API on another domain (https://api.example.com). - You need to control which external sites can access your API.
The server must explicitly allow such requests by sending specific HTTP headers, such as Access-Control-Allow-Origin.
Example of a header that allows access from any domain:
Access-Control-Allow-Origin: *
Or more securely — specify a particular domain:
Access-Control-Allow-Origin: https://app.example.com
In Java applications, CORS can be configured via filters or annotations, for example, using the Spring Framework:
@CrossOrigin(origins = "https://app.example.com")
@RestController
public class ApiController {
// controller methods
}
Thus, CORS is an important mechanism for secure interaction between client and server across different domains.