0

My goal is to debug why I can send HTTP GET request without RequestHeaders, but I can't send HTTP GET request with RequestHeaders, on browser.

I am following the spring.io's tutorial to learn more about CSRF and CORS.

What I've tried:

  1. Send GET Request to http://localhost:8080/user with Request Header Authorization: Basic ..... would return me CORS error
Access to XMLHttpRequest at 'http://localhost:8080/user' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  1. SEND GET Request to http://localhost:8080/user without a Request Header will not return me an CORS error.

Note: I've double check that CORS issue is resolved for any GET request if I did not add Request Header.

  @Bean
  CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }

However, it does not fix CORS issue if I send the GET /user with a Request Header Authorization: Basic ....

My expected result is: When I send a GET request with a Request Header, it should not return a CORS error.

My actual result is: It return a CORS error.

Jason Rich Darmawan
  • 1,607
  • 3
  • 14
  • 31
  • Do you have different configs for "Authorized" and public URL ? – gvmani Jan 14 '21 at 10:02
  • @gvmani I only override `configure(HttpSecurity http)` method from the `WebSecurityConfigurerAdapter` class. The Angular project and the Spring Security project lives on different port. Please feel free to clone [the full repository](https://github.com/kidfrom/learn-java/tree/main/etc/spring-security-angular). – Jason Rich Darmawan Jan 14 '21 at 10:09
  • this question might help https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application – gvmani Jan 14 '21 at 10:27

1 Answers1

0

If you use JDK 8+, there is a one solution:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}

Let me know if this works.

Ajay Negi
  • 322
  • 1
  • 7
  • I checked the `applyPermitDefaultValues()` source code. It should works. I decided to manually configure it [Spring Security's Reference](https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/cors.html). – Jason Rich Darmawan Jan 15 '21 at 09:19