Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure CORS and Basic Authorization in Spring Boot?

I'm trying to configure CORS in a Spring boot application that already has Basic auth set up.

I've searched in many places, including this answer, that points to Filter based CORS support in the official docs.

So far no luck.

My AJAX request is done this way. It works if done from same origin http://localhost:8080.

fetch('http://localhost:8080/api/lists', {
  headers: {
    'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
  }
}

The AJAX request is done from a React app at http://localhost:3000, so I tried the following Spring boot CORS config:

@Configuration
class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        // Maybe I can just say "*" for methods and headers
        // I just copied these lists from another Dropwizard project
        config.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
        config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept",
            "Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods",
            "Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age",
            "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alternates",
            "Content-Range", "Content-Disposition", "Content-Description"));
        config.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

My WebSecurityConfig:

@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and()
            .authorizeRequests()
            .antMatchers("/", "/index.html").permitAll()
            .anyRequest().fullyAuthenticated();
    }
}

The fetch call from http://localhost:3000 displays this 401 error in the console:

Fetch API cannot load http://localhost:8080/api/lists. Response for preflight has invalid HTTP status code 401.

enter image description here

An in the network tab of chrome dev tools I see this OPTIONS request:

enter image description here

like image 365
Ferran Maylinch Avatar asked Dec 10 '16 13:12

Ferran Maylinch


People also ask

How do I enable CORS spring boot?

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?

Controller Method CORS ConfigurationThis @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.

How can the 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.

What is CORS configuration?

A CORS configuration is a document that defines rules that identify the origins that you will allow to access your bucket, the operations (HTTP methods) supported for each origin, and other operation-specific information. In the S3 console, the CORS configuration must be a JSON document.


2 Answers

I think you need to allow OPTION requests into your web security config. Something like:

.antMatchers(HttpMethod.OPTIONS, "/your-url").permitAll()

like image 53
ilopezluna Avatar answered Oct 06 '22 22:10

ilopezluna


The browser checks CORS settings via a request with OPTIONS header. And if you've configured authorization, OPTIONS request will be blocked as unauthorized.

You can simply allow OPTIONS request via cors support in WebConfigurerAdapter.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        http.cors();
    }
}

Check this link for more info: https://www.baeldung.com/spring-security-cors-preflight

like image 30
Bogdan Fedoronchuk Avatar answered Oct 06 '22 22:10

Bogdan Fedoronchuk