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)
1 |
http.csrf().disable(); |
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
1 2 3 4 5 6 7 |
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); } } |
In this example, http.cors()
allows cross-origin requests, while http.csrf().disable()
turns off CSRF protection (use cautiously).
Common CORS Configuration
1 2 3 4 5 6 7 8 9 10 11 |
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("https://trusteddomain.com"); configuration.addAllowedMethod(HttpMethod.GET); configuration.addAllowedMethod(HttpMethod.POST); configuration.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } |
This configuration allows requests from https://trusteddomain.com
for specific HTTP methods.