spring-security - 多个@EnableGlobalMethodSecurity 注解

标签 spring-security spring-boot

如果多个配置类都有 @EnableGlobalMethodSecurity 注释,那么一个使用一个忽略吗?

在 Spring Boot 应用程序中,有两个 WebSecurityConfigurerAdapter 实例——一个用 @EnableGlobalMethodSecurity(secured = true) 注释,另一个用 @EnableGlobalMethodSecurity(prePostEnabled = true) 注释。但到目前为止,我无法使 @PreAuthorize 注释起作用。只有一个注释我可以看到验证它正在被应用。
例如

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class FirstConfigurer extends WebSecurityConfigurerAdapter {
...

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class AnotherConfiguration extends WebSecurityConfigurerAdapter{
...

spring-security 是否支持使用@EnableGlobalMethodSecurity 注解的多个配置类?
有没有办法查看实际配置的内容?

最佳答案

我调试它(​​到 springframework 源)以查看它正在加载的内容和顺序。

我遇到过类似的情况,我有一个配置 @EnableGlobalMethodSecurity(securedEnabled = true) 的库(我无法更改)。

我想使用 @EnableGlobalMethodSecurity(prePostEnabled=true)
发生的事情是库配置是通过我的配置加载的(只会使用最后一个加载的配置)

我尝试使用 @Order(Ordered.LOWEST_PRECEDENCE)@EnableGlobalMethodSecurity(order = Ordered.HIGHEST_PRECEDENCE, ... 但没有效果。

我的解决方案是通过在我的配置中导入库配置来设置我想要的顺序,如下所示:

@Import(LibraryConfig.class)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MyConfiguration extends GlobalMethodSecurityConfiguration {
    /* my code */
}

PLUS:我发现我的情况更复杂,因为我使用的库不止一次配置 @EnableGlobalMethodSecurity(securedEnabled = true)
所以行为有点不同,为了强制使用我的配置,我不得不覆盖这个方法的实现:
@Bean
public MethodSecurityMetadataSource methodSecurityMetadataSource() {
    return super.methodSecurityMetadataSource();
}

@Bean
public MethodInterceptor methodSecurityInterceptor() throws Exception {
    return super.methodSecurityInterceptor();
}

@Bean
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() {
    return super.preInvocationAuthorizationAdvice();
}

关于spring-security - 多个@EnableGlobalMethodSecurity 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37184904/

相关文章:

java - 针对客户和员工的 Spring Security 用户身份验证

mysql - 如何在Spring Boot中使用实体解决SQL语法错误?

java - Spring Boot : only for web application development?

java - Minikube/kubernetes pod 无法连接到 Mongodb Atlas

spring - log4j2 中 xwEx 的含义?

java - 为什么我使用 Spring Boot 得到 "NOAUTH Authentication required"?

java - 在 JSP EL 表达式中获取 Spring Security Principal

java - 发布后 Spring Security Access 被拒绝 403

java - 添加了 Spring Security,现在我得到 "No WebApplicationContext found: no ContextLoaderListener registered?"

grails - Spring Security Core插件-使用户 session 无效