我使用的是Spring Boot 2.0.2版 . 以下是我的安全配置
@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 .
3 回答
虽然Spring安全性提供了一种在http configurer中配置CORS的方法,但是有一种更简洁的方法可以将CORS过滤器添加到应用程序中 -
对具有最高优先级的过滤器进行排序可确保
javax.servlet.Filter
的MyCORSFilter实现是链中的第一个 . 希望这可以帮助好的,所以我意识到它已被弃用了 . 如果你看看baeldung它有更新方式,因为他们更新了webmvcconfigurer:
查看Spring的本指南:
https://spring.io/guides/gs/rest-service-cors/
在Spring Boot中添加CORS支持的方法很少 .
使用全局配置:
并使用
@CrossOrigin
注释: