in spring boot 2.3.3, facing issue regarding CORS. no spring security has been used

Viewed 210

"has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

getting this message when api is being hit by angular portion, but proper response is obtained when end point is being hit from POSTMAN.

1 Answers

You will need to enable/configure CORS (Cross-Origin Resource Sharing) in your spring boot application -

Enabling CORS for the whole application (This is a global configuration)-

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

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

Additionally Spring allows you to control CORS configuration at Controller as well as at the RequestMapping level -

To enable CORS for the whole controller -

@CrossOrigin(origins = "http://your-client-domain.com", maxAge = 3600)
@RestController
@RequestMapping("/booking")
public class BookingController {

    @RequestMapping("/{id}")
    public Booking retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

To enable the CORS for specific path mapping (RequestMapping) -

@RestController
@RequestMapping("/booking")
public class BookingController {

    @CrossOrigin(origins = "http://your-client-domain.com")
    @RequestMapping("/{id}")
    public Booking retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

You can also apply CORS configuration only for required mappings (paths), you can always configure it to the granular details -

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/v1/**")
            .allowedOrigins("http://your-client-domain.com")
            .allowedMethods("OPTIONS", "GET", "POST", "PUT", "DELETE")
            .allowedHeaders("Some-Header-x", "Authorization")
            .exposedHeaders("X-API-Limit")
            .allowCredentials(false).maxAge(3600);
    }
}

You can read more about enabling and configuring CORS in Spring Applications here

Related