【问题标题】:How to disable/ ignore @PreAuthorize in a Spring Boot application如何在 Spring Boot 应用程序中禁用/忽略 @PreAuthorize
【发布时间】:2020-01-27 19:53:25
【问题描述】:

我有一个提供 REST API 的 Spring Boot 应用程序。所有 API 都使用 Spring Security 进行保护。我还使用 @PreAuthorize 注释添加了方法授权。

对于本地开发,我想通过配置或其他方式完全禁用安全性。我想禁用身份验证和授权,以便我可以轻松调用 API,而无需在每次要调用 API 时获取新令牌。

禁用身份验证很容易,我只是将其添加到配置方法中,一切都很好。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/**");
}

但这会导致 AuthenticationCredentialsNotFoundException 在遇到我从身份验证中排除的端点时,这是有道理的。仅当我删除 @PreAuthorize 注释时,此异常才会消失,显然,每当我要进行一些本地开发工作时,我都不想这样做。似乎只是通过在方法上添加注释,Spring AOP 启动并检查 Spring Security Context 中的身份验证对象,并且没有办法禁用它而不是删除注释。

如何让 Spring 完全忽略 @PreAuthorize 注释?我尝试删除 @EnableGlobalMethodSecurity 但它对异常没有帮助。

【问题讨论】:

  • 你覆盖这个方法protected void configure(HttpSecurity http) throws Exception吗?如果是这样,请在问题中发布所有内容。
  • @EnableGlobalMethodSecurity(prePostEnabled = true) 是能够扫描@PreAuthorize 注释的注释。如果它不存在 - @PreAuthorize 注释不会做任何事情。
  • @improbable 这也是我所期望的,但是当我删除 EnableGlobalMethodSecurity PreAuthorize 注释时仍在被扫描。至少 AuthenticationCredentialsNotFoundException 肯定不会消失。
  • 发布您的整个安全配置。
  • @Vahid 删除 @EnableGlobalMethodSecurity 应该可以工作。也许还有另一个带有该注释的类?但是,您可以在 stackoverflow.com/questions/22176236/… 中找到更好的方法

标签: spring spring-boot spring-security authorization


【解决方案1】:

我遇到了同样的问题,我用下面的代码解决了:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Value("${security.enabled:true}")
  private boolean securityEnabled;


  @Override
  public void configure(WebSecurity web) throws Exception {
    if (!securityEnabled) {
      web.ignoring().antMatchers("/**");
    }
  }

  /**
   * ommit codes
   */

  /**
   * control @EnableGlobalMethodSecurity(prePostEnabled = true),to  solve AuthenticationCredentialsNotFoundException
   */
  @ConditionalOnProperty(prefix = "security",
    name = "enabled",
    havingValue = "true")
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  static class Dummy {
  }
}

如果security.enabled=falseDummy bean 将不会被创建,因此@EnableGlobalMethodSecurity(prePostEnabled = true) 也将不存在,最后@PreAuthorize 注释将被忽略。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 2017-03-31
    • 2016-07-16
    • 2017-06-22
    • 2017-11-06
    • 2023-03-16
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多