如何解决弹簧启动 + MSAL 和角度'has been blocked by CORS policy'?



Spring boot with Microsoft authentication library (azure AD) authentication。Angular客户端访问API端点时会得到一个错误"被CORS策略阻止了"。对飞行前请求的回应不通过访问……"这里应用程序有一个安全配置,MSAL库也有一个安全配置。

尝试这些方法

  1. 在应用SecurityConfig
  2. 中添加了@Order(3)
  3. 在应用安全配置
  4. 中增加了antMatchers(HttpMethod.OPTIONS).permitAll()
  5. @CrossOrigin(起源="http://localhost: 4200")

为了将来的参考,这在Spring安全参考手册中有介绍。

在我看来,你在问题中列出的东西听起来不像是完整的解决方案。相反,首先要记住,CORS是JavaScript应用程序和服务器之间的契约——JavaScript应用程序想要发送的任何origin、header或方法都需要在服务器端被允许。

其次,对应用程序进行两个更改。更新您的安全配置以包含cors指令:

http
.authorizeRequests((requests) -> requests.anyRequest().authenticated())
// ...
.cors(Customizer.withDefaults())
// ...

然后发布像这样的CorsConfigurationSource@Bean:

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

相关内容

最新更新