我正在使用 Spring Boot 版本 2.0.2Release。以下是我的安全配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
@ComponentScan("com.mk")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationProvider myAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors().configurationSource(corsConfigurationSource())
.and()
.csrf().disable()
.anonymous().and()
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/index.html").permitAll()
.antMatchers(HttpMethod.POST,"/login").permitAll()
.antMatchers(HttpMethod.GET,"*").authenticated()
.and().httpBasic();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
由于 CORS 问题,我无法调用任何 API(包括登录 permitAll)。
在我得到的浏览器上(它适用于 Postman,因为那里没有进行 CORS 检查)
无法加载 http://localhost:8080/myurl :对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:4200 ”。响应具有 HTTP 状态代码 403。
原文由 Mohit Kanwar 发布,翻译遵循 CC BY-SA 4.0 许可协议
尽管 Spring security 提供了一种在 http 配置器中配置 CORS 的方法,但有一种更简洁的方法可以将 CORS 过滤器添加到应用程序中——
以最高优先级排序过滤器可确保
javax.servlet.Filter
的 MyCORSFilter 实现是链中的第一个。希望这可以帮助