如何在 Spring Boot 应用程序中禁用/忽略 @PreAuthorize

Vah*_*hid 6 spring authorization spring-security spring-boot

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

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

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

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

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

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

NiY*_*hun 8

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

\n
@Configuration\n@EnableWebSecurity\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n  @Value("${security.enabled:true}")\n  private boolean securityEnabled;\n\n\n  @Override\n  public void configure(WebSecurity web) throws Exception {\n    if (!securityEnabled) {\n      web.ignoring().antMatchers("/**");\n    }\n  }\n\n  /**\n   * ommit codes\n   */\n\n  /**\n   * control @EnableGlobalMethodSecurity(prePostEnabled = true)\xef\xbc\x8cto  solve AuthenticationCredentialsNotFoundException\n   */\n  @ConditionalOnProperty(prefix = "security",\n    name = "enabled",\n    havingValue = "true")\n  @EnableGlobalMethodSecurity(prePostEnabled = true)\n  static class Dummy {\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n