CORS configuration in Spring Security Rest APIs

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:

Step 1: Add Dependencies

                
        <!-- Maven dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
                
            

Step 2: Configure CORS in SecurityConfig

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:
  • @Bean public CorsConfigurationSource corsConfigurationSource(): Defines a CORS configuration bean.
  • configuration.addAllowedOrigin("*"): Allows requests from any origin. Adjust this to your specific domain or origins.
  • configuration.addAllowedMethod("*"): Allows all HTTP methods.
  • configuration.addAllowedHeader("*"): Allows all headers.
  • configuration.setAllowCredentials(true): Allows credentials such as cookies. Adjust according to your needs.

Step 3: Allow CORS in Controller

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.

Step 4: Run the Application

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.

Note:

  • Customize CORS configurations based on your specific requirements.
  • Be cautious with the use of * for allowed origins, especially in production. Specify specific origins for increased security.
  • Ensure that your CORS configuration aligns with your overall security policies.

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.