,

How to avoid cross-origin resource sharing (CORS) issues in your Spring Boot APIs

Posted by

Cross-origin resource sharing (CORS) is a mechanism that allows web pages from one domain or origin to access resources from another domain. this is a security feature implemented by web browsers to prevent unauthorized access to resources, such as APIs or web pages, that are hosted on a different domain.

When a web page makes a request to a resource on a different domain, the browser sends a CORS request to the server hosting the resource, asking if the request is allowed. The server responds with a set of CORS headers that specify which domains are allowed to access the resource, what HTTP methods are allowed, and what headers can be sent in the request.

If the server allows the request, the browser will allow the web page to access the resource. If the request is not allowed, the browser will block the request and the web page will not be able to access the resource.

CORS is an important security feature that helps prevent cross-site scripting (XSS) attacks and other security vulnerabilities that can be exploited by malicious actors. It is widely used in web development to enable web applications to access resources from different domains while maintaining a secure and trusted environment.

To avoid cross-origin resource sharing (CORS) issues in your Spring Boot API, you can configure your application to allow cross-origin requests from specific domains or all domains. Here are the steps to follow in integrating on Spring Boot Code:

Add the following dependencies to your project:

implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web-services'

Create a @RestController class and add @CrossOrigin annotation to it:

@RestController @CrossOrigin(origins = "http://example.com") public class MyController { // ... } 

This will allow requests from the http://example.com domain. You can specify multiple domains by separating them with commas, or use the * wildcard to allow requests from all domains.

If you want to configure CORS globally for your application, you can create a WebMvcConfigurer bean

@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } }; }

This will allow requests from the http://example.com domain and allow the specified HTTP methods and headers.

Besides the @CrossOrigin annotation and the WebMvcConfigurer bean, there are other configurations you can use in Spring Boot to avoid cross-origin resource sharing (CORS) issues. Here are some examples:

  1. Configure CORS using properties

You can configure CORS in your application.properties file by adding the following properties:

# Allowed CORS origins
spring.webmvc.cors.allowed-origins=http://example.com

# Allowed CORS methods
spring.webmvc.cors.allowed-methods=GET,POST,PUT,DELETE

# Allowed CORS headers
spring.webmvc.cors.allowed-headers=*

# Enable/disable CORS support
spring.webmvc.cors.enabled=true

This will allow requests from the http://example.com domain and allow the specified HTTP methods and headers.

  1. Configure CORS using a filter

You can create a filter to handle CORS requests in your Spring Boot application. Here’s an example:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (!"OPTIONS".equals(request.getMethod())) {
            chain.doFilter(req, res);
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    // ...
}

This filter will allow requests from all domains (*) and allow the specified HTTP methods and headers.

  1. Configure CORS using Spring Security

If you’re using Spring Security in your application, you can configure CORS using the cors() method in your WebSecurityConfigurerAdapter. Here’s an example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .cors();
    }

    @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;
    }
}

This will allow requests from the http://example.com domain and allow the specified HTTP methods and headers.

  1. Configure CORS using a WebFilter

You can use a WebFilter instead of a Filter to handle CORS requests. Here’s an example:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
        headers.add("Access-Control-Allow-Headers", "*");
        headers.add("Access-Control-Max-Age", "3600");
        headers.add("Access-Control-Allow-Credentials", "true");

        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        } else {
            return chain.filter(exchange);
        }
    }
}

This filter will allow requests from all domains (*) and allow the specified HTTP methods and headers.

  1. Configure CORS using annotations

You can also use annotations to configure CORS on your controller methods. Here’s an example:

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://example.com", maxAge = 3600)
public class MyController {

    @GetMapping("/data")
    public List<Data> getData() {
        // ...
    }

    // ...
}

This will allow requests from the http://example.com domain and set the maximum age of the CORS response headers to 3600 seconds.

  1. Configure CORS globally

You can configure CORS globally for your entire application using the CorsRegistry in your WebMvcConfigurer bean. Here’s an example:

typescriptCopy code@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("http://example.com")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("*")
            .allowCredentials(true)
            .maxAge(3600);
    }

    // ...
}

This will allow requests from the http://example.com domain and allow the specified HTTP methods and headers for all paths (/**) in the application.

Conclusion

Note:-that allowing requests from all domains using the * wildcard can be a security risk, so it’s recommended to only allow specific domains that you trust.

how you can configure CORS in your Spring Boot application.will depend on your specific use case and requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *