Explore Topics

CSRF Protection & CORS

CSRF Protection (Cross-Site Request Forgery) and CORS (Cross-Origin Resource Sharing) are essential security concepts when building web applications.

CSRF Protection

CSRF is an attack where a malicious actor tricks a user into making unwanted requests to a server where they are authenticated. This can lead to actions like unauthorized money transfers or changing user data without the user’s knowledge.

Spring Security automatically provides CSRF protection by generating a unique token for every form or AJAX request. This token is then included in the request to verify that it came from the legitimate user.

Disabling CSRF Protection (not recommended for most apps)

This is not recommended for production environments unless you are using a stateless authentication method like JWT.

CORS (Cross-Origin Resource Sharing)

CORS is a security feature that restricts how web browsers make requests to domains other than the one from which the page was loaded. For example, if your frontend is hosted on example.com and your API on api.example.com, CORS ensures that only trusted origins can access the API.

Spring Security can be configured to allow or restrict cross-origin requests. By default, it blocks cross-origin requests for security purposes. You can enable and configure CORS to allow specific domains to interact with your server.

Configuring CORS in Spring Security

In this example, http.cors() allows cross-origin requests, while http.csrf().disable() turns off CSRF protection (use cautiously).

Common CORS Configuration

This configuration allows requests from https://trusteddomain.com for specific HTTP methods.