Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Spring for CORS

I'm trying to configure Spring for CORS in order to use Angular web UI:

I tried this:

@Configuration
@ComponentScan("org.datalis.admin.config")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        PropertySourcesPlaceholderConfigurer conf = new PropertySourcesPlaceholderConfigurer();
        conf.setLocation(new ClassPathResource("application.properties"));
        return conf;
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("127.0.0.1");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

Apache server with Angular FE is running with Wildly server on the same server so I configured 127.0.0.1 for source.

But still I get:

Access to XMLHttpRequest at 'http://123.123.123.123:8080/api/oauth/token' from origin 'http://123.123.123.123' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
auth:1 Failed to load resource: the server responded with a status of 404 (Not Found)

Do you know how I can fix this issue?

Second way that I tried:

@Configuration
@EnableResourceServer
public class ResourceSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("resource_id").stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/users/**").permitAll()
                .anyRequest().authenticated()
                .and()
        .cors().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .anyRequest()
        .fullyAuthenticated()
        .and()
        .httpBasic()
        .and()
        .csrf().disable();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSources() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

With the second configuration I get has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. auth:1 Failed to load resource: the server responded with a status of 404 (Not Found)

What is the best way to achieve this result?

like image 874
Peter Penzov Avatar asked Jan 18 '19 14:01

Peter Penzov


People also ask

How do I enable CORS in Spring security?

Enabling CORS Configuration Globally in Spring Webflux To define CORS globally in a Spring Webflux application, we use the WebfluxConfigurer and override the addCorsMappings() . Similar to Spring MVC, it uses a CorsConfiguration with defaults that can be overridden as required.

What is CORS configuration in Spring boot?

Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.

How do I set Access-Control allow origin in Java Spring boot?

Try adding this to your application: @SpringBootApplication @RestController public class ChrisboltonServiceApplication { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry. addMapping("/**").

How can CORS configuration be enabled for controller method?

27.2 Controller method CORS configuration You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it.


2 Answers

Your allowed origin is 127.0.0.1 but your client side has the ip 123.123.123.123. Try to change this:

config.addAllowedOrigin("127.0.0.1");

To this:

config.addAllowedOrigin("123.123.123.123");
like image 187
Raphael Alves Avatar answered Sep 20 '22 14:09

Raphael Alves


You need to tell Spring Security to use the CORS Configuration you created.

In my project I configured Spring Security in this way:

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http
        .authorizeRequests()
        .antMatchers("/rest/protected/**")
        .authenticated()
     //Other spring sec configruation and then:
    .and()
        .cors()
        .configurationSource(corsConfigurationSource())

}

Where corsConfigurationSource() is:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        boolean abilitaCors = new Boolean(env.getProperty("templating.oauth.enable.cors"));
        if( abilitaCors )
        {
            if( logger.isWarnEnabled() )
            {
                logger.warn("CORS ABILITATI! Si assume ambiente di sviluppo");
            }
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:8080", "http://localhost:8180"));
            configuration.setAllowedMethods(Arrays.asList(  RequestMethod.GET.name(),
                    RequestMethod.POST.name(), 
                    RequestMethod.OPTIONS.name(), 
                    RequestMethod.DELETE.name(),
                    RequestMethod.PUT.name()));
            configuration.setExposedHeaders(Arrays.asList("x-auth-token", "x-requested-with", "x-xsrf-token"));
            configuration.setAllowedHeaders(Arrays.asList("X-Auth-Token","x-auth-token", "x-requested-with", "x-xsrf-token"));
            source.registerCorsConfiguration("/**", configuration);
        }
        return source;
    }

I hope it's useful

Angelo

like image 28
Angelo Immediata Avatar answered Sep 21 '22 14:09

Angelo Immediata