CORS with Spring Security 6

Anh Trần Tuấn - Sep 3 - - Dev Community

1. Introduction to CORS

1.1 What is CORS?

Image

CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented by web browsers to prevent websites from making unauthorized requests to different domains. CORS uses HTTP headers to specify which origins are allowed to access resources on a web server.

1.2 Why is CORS Important?

CORS is essential for securing web applications by controlling cross-origin requests. Without proper CORS configuration, your application could be vulnerable to security threats like Cross-Site Request Forgery (CSRF) and Cross-Site Scripting (XSS). Configuring CORS correctly helps ensure that only trusted domains can access your resources.

2. Configuring CORS in Spring Security 6

Spring Security 6 provides a modern approach to configuring CORS using the SecurityFilterChain and CorsConfigurationSource interfaces. This setup offers a clean and flexible way to manage CORS policies.

2.1 Basic Configuration

To start with, here’s a basic example of how to configure CORS in a Spring Boot application using Spring Security 6:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(c -> c.configurationSource(corsConfigurationSource()))
            .csrf().disable()
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We configure CORS to allow requests from http://example.com
  • We specify the allowed HTTP methods and headers.
  • We enable credentials to allow cookies and authentication headers.

2.2 Advanced Configuration

For more sophisticated requirements, such as allowing specific headers and exposing additional headers, you can enhance your CORS configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(c -> c.configurationSource(corsConfigurationSource()))
            .csrf().disable()
            .authorizeRequests(authorizeRequests ->
                authorizeRequests.anyRequest().authenticated()
            );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setExposedHeaders(Arrays.asList("Authorization", "Content-Type"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this advanced configuration:

  • We’ve added exposed headers to allow the Authorization and Content-Type headers to be visible in the response.
  • This setup is useful for applications that need to handle custom headers or tokens.

3. Testing Your CORS Configuration

Once you’ve set up CORS, it’s crucial to test whether it’s working as expected. Here’s how you can do that:

3.1 Using Postman

  • Open Postman and create a new request.
  • Set the request method to GET and enter your API endpoint.
  • Under the Headers tab, add a new header Origin with the value http://example.com.
  • Send the request and check the response headers for the Access-Control-Allow-Origin header.

Example Result

You should see a response header like this:

Access-Control-Allow-Origin: http://example.com
Enter fullscreen mode Exit fullscreen mode

3.2 Using Browser Developer Tools

  • Open your web application in a browser.
  • Open the browser’s developer tools (F12 or right-click and select “Inspect”).
  • Go to the Network tab and make a request to your API.
  • Check the response headers to ensure that Access-Control-Allow-Origin is present and correctly set.

Example Result

In the Network tab, under the Headers section, you should see:

Access-Control-Allow-Origin: http://example.com
Enter fullscreen mode Exit fullscreen mode

4. Conclusion

Configuring CORS in Spring Security 6 is a crucial step for managing cross-origin requests securely. By using the SecurityFilterChain and CorsConfigurationSource, you can easily set up and customize your CORS policies. Testing your configuration ensures that your setup is working as expected and that your application remains secure.

With this setup, you can ensure that your Spring Security 6 application is well-protected and interacts seamlessly with trusted domains.

Read posts more at : CORS with Spring Security 6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player