首页 > 解决方案 > 从源“http://localhost:4200”访问“http://localhost:8080/api/auth/userdetails”的 XMLHttpRequest 已被 CORS 策略阻止

问题描述

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

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

它在邮递员中运行良好。

在此处输入图像描述

我正在尝试从 Angular 调用它。

在此处输入图像描述

登录表单工作正常。

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

这是网络安全配置器

 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 中工作。

我错过了什么?

标签: spring-bootionic-framework

解决方案


将 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()...
}

推荐阅读