java - 设置 Spring 方法安全性默认为经过身份验证
问题描述
我正在尝试让 Spring Boot 使用以下规范:
- 访问控制应该包含在每个控制器类中,而不是集中在“http.antMatcher(..”语句中。
- 如果程序员没有在控制器方法中包含访问控制细节,它应该默认为“任何经过身份验证的用户”
- 应该可以将某些方法表示为“公共”,未经身份验证的用户可以使用。
这是我的示例控制器:
@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 |
如果任何人都无法使用未注释的方法(粗心),这也是可以接受的。
我怎样才能得到想要的行为?
解决方案
推荐阅读
- javascript - Angular 2+ 项目不接受外部 js 文件
- json - 在 powershell 中显示 Json 嵌套数组
- java - 是否可以在没有重复值的情况下打印此二维数组?
- html - 网格项不会占用父容器的全高
- c# - AutoMapper 映射一个子列表对象
- html - AngularJS如何保持下拉列表中的选择打开
- java - 具有基于仲裁的同步复制的 JDBC Postgres 故障转移
- java - JAVA NIO 服务器 - 未收到客户端空白消息/部分消息
- php - 为 AJAX 请求并行获取 Apache PHP 响应
- python - 不同长度的熊猫系列