Spring security 在spring boot中使用多个WebSecurity配置适配器
我有两个类扩展了Spring security 在spring boot中使用多个WebSecurity配置适配器,spring-security,spring-boot,Spring Security,Spring Boot,我有两个类扩展了websecurityConfigureAdapter。不能让他们一起工作 其思路如下: 有一个websecurityConfigureAdapter,它只向安全链添加自定义筛选器。过滤器执行一些自定义身份验证,并将身份验证保存到SecurityContext中。这通常效果很好。配置如下(忽略导入): 订单(1) @配置 @启用WebMVC安全性 公共类BestSecurityConfig扩展了WebSecurity配置适配器{ @自动连线 私有BestPreAuthentica
websecurityConfigureAdapter
。不能让他们一起工作
其思路如下:
websecurityConfigureAdapter
,它只向安全链添加自定义筛选器。过滤器执行一些自定义身份验证,并将身份验证
保存到SecurityContext
中。这通常效果很好。配置如下(忽略导入):@ComponentScan
包含它,并对自定义身份验证进行排序。显然,他们希望提供定制的HttpSecurity
来保护edpoints。尝试类似于:@配置
@EnableGlobalMethodSecurity(securedEnabled=true,Prespenabled=true)
@顺序(SecurityProperty.ACCESS\u OVERRIDE\u顺序)
公共类SecurityConfig扩展了WebSecurity配置适配器{
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.csrf().disable()
.授权请求()
.antMatchers(“/testUrl”).hasRole(“不存在”)
.anyRequest().authenticated();
}
}
显然,测试URL不应可访问,因为我的用户不是角色不存在的成员。不幸的是她是
如果我将安全authorizeRequests()
部分移动到配置类表单1中。在添加安全过滤器之后,它会按预期阻止访问。但在我的例子中,看起来第二个配置被忽略了
我还调试了configure()
任何提示我如何才能使这项工作非常感谢
目标概述:
- 有一个
WebSecurityConfigurerAdapter
,它添加了过滤器并对库用户隐藏
- 让用户定义自己的自定义端点安全性
Spring boot 1.1.6-RELEASE所以我刚刚找到的一个选项是:
从第一个bean中删除@Configuration
注释
并更改2。致:
@配置
@EnableGlobalMethodSecurity(securedEnabled=true,Prespenabled=true)
@顺序(SecurityProperty.ACCESS\u OVERRIDE\u顺序)
公共类SecurityConfig扩展了BestSecurityConfig{//注意更改的扩展!
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
super.configure(http);//合并两个http配置
http
.csrf().disable()
.授权请求()
.antMatchers(“/testUrl”).hasRole(“不存在”)
.anyRequest().authenticated();
}
}
任何关于这是正确的还是错误的方法的评论都将不胜感激
编辑:几年后,我仍然没有找到其他方法,但我越来越喜欢这种方法。即使在默认情况下扩展抽象websecurityConfigureAdapter
,也没有理由说其他抽象层不能提供另一个提供有意义的默认值的抽象扩展。通过使用可以更清晰地构造一些默认配置,并简化在新项目中的集成
我用它来配置JWT身份验证过滤器,但我认为CORS过滤器更简单,更具教育意义:
公共类CustomCorsFilterDsl扩展了AbstractHttpConfigurer{
@凌驾
public void init(HttpSecurity http)引发异常{
//您的初始化代码在这里,在这种情况下不需要
}
@凌驾
public void configure(HttpSecurity http)引发异常{
CorsFilter CorsFilter=CorsFilter(corsProperties);
addFilterBefore(corsFilter,UsernamePasswordAuthenticationFilter.class);
}
私人公司过滤器公司过滤器(公司财产公司财产){
UrlBasedCorsConfigurationSource=新的UrlBasedCorsConfigurationSource();
CorsConfiguration配置=新的CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(“http://localhost:9000");
config.addAllowedHeader(“*”);
config.addAllowedMethod(“GET、POST、PUT、PATCH、DELETE”);
source.registerCorsConfiguration(“/**”,config);
返回新的过滤器(来源);
}
公共静态CustomCorsFilterDsl(){
返回新的CustomCorsFilterDsl();
}
}
在您的Web安全配置中,您可以这样使用它:
@配置
@启用Web安全性
公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
@凌驾
受保护的无效配置(HttpSecurity http)t