CORS策略已阻止从来源“ http:// localhost:4200”访问“ http:// localhost:8080 / api / auth / userdetails”处的XMLHttpRequest

问题描述

我已经创建了一个REST服务进行身份验证,并且成功。

我创建了另一个服务,并通过传递令牌来调用该服务。

在邮递员中工作正常。

enter image description here

我正试图从Angular调用它。

enter image description here

登录表单工作正常。

loginURL: string = 'localhost:8080/authenticate';

this.http.post(this.loginURL,{
    username: 'headoffice',password: 'guest'
}).subscribe((successResp) => {
        resolve(successResp);
    },(errorResp) => {
        resolve(errorResp);
    }
);

但是当我呼叫localhost:8080 / api / auth / userdetails

userDetailsURL: string = 'localhost:8080/api/auth/userdetails';
token: string = '.....';

this.http.post(this.userDetailsURL,null,{
    headers: new HttpHeaders({
        'Authorization': 'Bearer ' + token
    })
}).subscribe((successResp) => {
        resolve(successResp);
    },(errorResp) => {
        resolve(errorResp);
    }
);

我遇到类似的错误

Access to XMLHttpRequest at 'http://localhost:8080/api/auth/userdetails' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone-evergreen.js:2845 POST http://localhost:8080/api/auth/userdetails net::ERR_Failed

这是websecurityconfigurer

 protected void configure(HttpSecurity httpSecurity) throws Exception {
     httpSecurity.csrf().disable().authorizeRequests()
         .antMatchers("/authenticate").permitAll().anyRequest()
         .authenticated().and().exceptionHandling()
         .authenticationEntryPoint(jwtAuthenticationEntryPoint)
         .and().sessionManagement()
         .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
         .addFilterBefore(customJwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
 }

这是WebMvcConfigurer

 public void addCorsMappings(CorsRegistry registry) {
     registry.addMapping("/**")
         .allowedMethods("GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","TRACE","CONNECT")
         .allowedOrigins("http://localhost:4200");
 }

请帮帮我。

为什么它在邮递员中工作而不在Angular中工作。

我想念什么?

解决方法

将CORS与Spring Security结合使用时,您必须在安全性配置中再执行一步,以使其生效。这是因为必须先处理CORS。

https://www.baeldung.com/spring-cors#cors-with-spring-security

在安全配置中,必须先调用cors,然后再进行其他逻辑操作

protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.cors().and()...
}