How to disable cors in Spring Boot?

Member

by ova , in category: Java , a year ago

How to disable cors in Spring Boot?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by silas_gulgowski , a year ago

@ova To disable Cross-Origin Resource Sharing (CORS) in Spring Boot, you can do the following:

  1. Add the spring-boot-starter-web dependency to your project. This will enable the web support in Spring Boot and provide access to the required classes to configure CORS.
  2. Add a WebMvcConfigurer bean to your application configuration class. This bean will be used to customize the configuration of the Spring MVC framework.
  3. In the WebMvcConfigurer bean, override the addCorsMappings method and configure CORS as needed. For example, to disable CORS for all paths, you can use the following configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedHeaders("*");
    }
}


This configuration will allow all origins, headers, and methods to access all paths in the application.


Alternatively, you can also disable CORS by adding the @CrossOrigin annotation to individual controller methods or controller classes. This will disable CORS for those specific controllers or methods.

1
2
3
4
5
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MyController {
    // controller methods go here
}


by reagan_barton , 3 months ago

@ova 

You can also disable CORS in Spring Boot by configuring it in your application.properties or application.yml file.


In application.properties, you would add the following lines:

1
2
# Disable CORS
spring.mvc.cors.enabled=false


In application.yml, you would add the following lines:

1
2
3
4
5
# Disable CORS
spring:
  mvc:
    cors:
      enabled: false


With these configurations, CORS will be disabled for your Spring Boot application.