Spring Boot - Enable CORS

Spring boot provides a simple way to enable CORS (Cross-Origin Resource Sharing) for your RESTful API.

CORS is a security feature implemented by browsers to prevent malicious websites from making requests to your server. By default, browsers will block requests from different origins, but you can enable CORS to allow requests from specific origins.

Enable CORS

To enable CORS in your Spring Boot application, you can use the @CrossOrigin annotation on your controller class or method. The @CrossOrigin annotation allows you to specify the origins that are allowed to access your API.

1
2
3
4
5
6
7
8
9
10
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class UserController {

@GetMapping("/users")
public List<User> getUsers() {
// Get users from the database
return userRepository.findAll();
}
}

You can also enable CORS at the method level.

1
2
3
4
5
6
7
8
9
10
@RestController
public class UserController {

@GetMapping("/users")
@CrossOrigin(origins = "http://localhost:3000")
public List<User> getUsers() {
// Get users from the database
return userRepository.findAll();
}
}

Configuration

You can also configure CORS globally for your application by adding a WebMvcConfigurer bean to your application context.

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class WebConfig implements WebMvcConfigurer {

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

or you can use a WebMvcConfigurer bean to configure CORS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}

Reference