Configuring Cross-Origin Resource Sharing (CORS) in Spring Security for REST APIs is crucial when dealing with requests from different origins. CORS enables or restricts cross-origin HTTP requests, providing control over which origins can access resources on your server. Below is a guide on how to configure CORS in Spring Security:
<!-- Maven dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
In your SecurityConfig class (or wherever you configure Spring Security), add a CorsConfigurationSource bean to define CORS configurations.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... other configurations
.cors(); // Enable CORS support
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*"); // Allow requests from any origin
configuration.addAllowedMethod("*"); // Allow all HTTP methods
configuration.addAllowedHeader("*"); // Allow all headers
configuration.setAllowCredentials(true); // Allow credentials (e.g., cookies)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
In this example:
Additionally, you can use the @CrossOrigin annotation on your controller methods to further customize CORS for specific endpoints.
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "https://vikasteck.com")
public class MyController {
@GetMapping("/resource")
public ResponseEntity<String> getResource() {
// Implementation details
}
}
In this example, the getResource endpoint allows requests only from https://vikasteck.com.
After configuring CORS, run your Spring Boot application. The CORS headers will be included in the responses, allowing specified origins to access your REST APIs.
This example provides a basic setup for configuring CORS in Spring Security for REST APIs. Adjustments may be needed based on your specific use case and security requirements.