【发布时间】:2018-03-10 22:58:40
【问题描述】:
我想结合基于角色的注释和基于模式的授权配置。
我希望基于模式的授权是“在未指定注释的情况下的回退”。
带注释的方法端点示例:
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
@RequestMapping(
method = RequestMethod.POST,
headers = "Accept=application/json",
path="publicApi/doWork" )
public void doWork() {
...
}
我的基于模式的授权配置如下:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
// specifies actuator endpoints should be secured by this config
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private void configureEndpointRoles(HttpSecurity http) throws Exception {
http.authorizeRequests().
antMatchers(anonymousUrlPatterns()).permitAll().
antMatchers("/publicApi/**").access("hasAnyRole('ROLE_ADMIN')").
anyRequest().denyAll();
;
}
}
这是我想要的工作方式:
- 如果端点 URL 匹配任何“anonymousUrlPatterns” - 允许。
- 如果端点匹配“publicApi”模式并使用
@PreAuthorize进行注释,则使用注释中的定义来决定用户是否可以访问它(在这种情况下,用户需要 ADMIN 或 USER 角色)。李> - 如果端点与“publicApi”模式匹配但没有注释,则用户必须具有 ADMIN 角色才能访问它。
- 如果端点不符合上述条件 - 拒绝。
我将如何定义这种行为?
按照指定的上述设置,基于模式的配置优先并且端点调用被拒绝(我不确定是基于模式的配置优先还是 Spring 是否以某种方式组合它们?)
春季版 - 4.2.3
更新:我已尝试将 EnableGlobalMethodSecurity 更新为:
@EnableGlobalMethodSecurity(
prePostEnabled = true,
order = Ordered.HIGHEST_PRECEDENCE)
但这似乎并没有改变行为。
【问题讨论】:
-
AFAIK 这是不可能的。也许您可以编写
GlobalMethodSecurityConfiguration的子类并返回自定义MethodSecurityMetadataSource。但是你不能在网络安全中配置你的默认值,你已经使用了另一个来源。