CORS semi working between Angular App and Spring b

2019-06-12 11:04发布

Following this Spring tutorial I've added the following bean to my configuration logic. Note that I am using Spring Boot.

If you are using Spring Boot, it is recommended to just declare a WebMvcConfigurer bean as following:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**") 
                    // Just slightly modified
                    .allowedMethods("HEAD", "GET", "PUT", "POST", 
                                    "DELETE", "PATCH", "OPTIONS")
                    .allowedOrigins("*")
                    .allowedHeaders("*");
        }
    };
}

Here's the thing: I am able to register a user from the client side:

onSubmit() {
  this.http.post('http://localhost:8080/register', this.registerForm.value)
    .subscribe(
      data => this.onRegisterSuccess(),
      err => alert(err.error.message)
    );
}

but I cannot access the endpoint for my OAuth2 token:

onSubmit() {
  const headers = new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded')
    .set('Authorization', 'Basic dGVzdGp3dGNsaWVudGlkOlhZN2ttem9OemwxMDA=');

  this.http.post('http://localhost:8080/oauth/token', this.loginForm.value, {headers: headers})
    .subscribe(
      data => this.onLoginSuccess(),
      err => alert(err.error.message)
    );
}

The resulting conversation:

enter image description here

I have no idea what the problem is.

1条回答
戒情不戒烟
2楼-- · 2019-06-12 11:52

The authorization header is special. You need to add with a different method

.allowCredentials(false)

查看更多
登录 后发表回答