CORS Support

Cross-Origin Resource Sharing (CORS) (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

We won't be creating full-fledged projects in this section to explain the working of CORS. We will use code snippets and will explain each bit of code so that the section is concise.

Change your Spring Security configuration, as shown in the following code snippet:

@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource urlCorsConfigSrc = new
UrlBasedCorsConfigurationSource();
urlCorsConfigSrc.registerCorsConfiguration("/**",
new CorsConfiguration().applyPermitDefaultValues());
return urlCorsConfigSrc;
}
}

In the preceding code, we configure CORS in the Spring Security configure method. We then create a new bean, corsConfigurationSource, in which we enable the /** path to be accessible by other domains. This is not really ideal in many scenarios, and the following code snippet shows the more enhanced CorsConfiguration class:

CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(new ArrayList<String>(Arrays.asList("*")));
configuration.setAllowedHeaders(new ArrayList<String>
(Arrays.asList("Authorization", "Cache-Control", "Content-Type")));
configuration.setAllowedMethods(new ArrayList<String>(Arrays.asList("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH")));
configuration.setAllowCredentials(true);

If it is a Spring MVC application, you can have a Spring MVC configuration file in which you can specify CORS mapping by creating a bean, as shown here:

@Configuration
public class SpringMVCConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE",
"PATCH","OPTIONS");
}
};
}
}

I have copied a previous example from Chapter 2Deep Diving into Spring Security, and created a new project in this chapter, containing full source code in spring-boot-in-memory-basic-authentication-with-cors. What we have done here is set the CORS global configuration by declaring the CorsConfigurationSource bean.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.59