首页 > 解决方案 > 设置 Spring 方法安全性默认为经过身份验证

问题描述

我正在尝试让 Spring Boot 使用以下规范:

这是我的示例控制器:


@Controller
public class ExampleController {

  // this should be available for everyone
  @PreAuthorize("permitAll()")
  @RequestMapping("/")
  @ResponseBody
  public String home() {
    return "Welcome home!";
  }

  // available to every authenticated user
  @PreAuthorize("isAuthenticated()")
  @RequestMapping("hello")
  @ResponseBody
  public String hello() {
    return "world";
  }

  // here we forgot to add Preautorize annotation
  // It should default to Authenticated or not available at all
  @RequestMapping("careless")
  @ResponseBody
  public String careless() {
    return "programmer";
  }

  // this should be available for everyone too
  @PreAuthorize("permitAll()")
  @RequestMapping("free")
  @ResponseBody
  public String free() {
    return "willy";
  }  

}

我尝试了许多不同的配置,但都没有按预期工作。

以下是最相关的,最后附有比较汇总表。

解决方案 1 - 无覆盖 创建一个扩展 WebSecurityConfigurerAdapter 的类而不覆盖任何内容并设置 EnableGlobalMethodSecurity。


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends WebSecurityConfigurerAdapter {

}

它不起作用,Springs 需要登录才能进行所有操作。

解决方案 2 - 用空方法覆盖

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends WebSecurityConfigurerAdapter {
  protected void configure(final HttpSecurity http) throws Exception {}  
}

它不起作用,因为如果方法没有注释,Spring 默认为“public”。

解决方案 3 - 配置覆盖

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends WebSecurityConfigurerAdapter {
  protected void configure(final HttpSecurity http) throws Exception {
    http.antMatcher("/**")  
    .authorizeRequests()  
    .antMatchers("/").permitAll()  
    .anyRequest().authenticated()
    .and().formLogin(); 
  }  
}

它不起作用,Spring 不允许使用“permitAll”注释公开方法。

总之:

|          | Wanted     | Sol-1 no | Sol-2 empty | Sol-3 config. |
|          | Behavior   | override | override    | override      |
|----------|------------|----------|-------------|---------------|
| home     |  public    |  login   |  public     | public        |
| hello    |  login     |  login   |  login      | login         |
| careless |  login     |  login   |  public     | login         |
| free     |  public    |  login   |  public     | login         |

如果任何人都无法使用未注释的方法(粗心),这也是可以接受的。

我怎样才能得到想要的行为?

标签: javaspringspring-bootspring-security

解决方案


推荐阅读