【发布时间】:2018-12-11 04:14:14
【问题描述】:
我已经实现了一个自定义身份验证过滤器,效果很好。在设置会话并将身份验证对象添加到安全上下文后,我使用外部身份提供程序并重定向到我最初请求的 URL。
安全配置
@EnableWebSecurity(debug = true)
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
// this is needed to pass the authentication manager into our custom security filter
@Bean
@Override
AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean()
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.antMatchers("/admin/test").hasRole("METADATA_CURATORZ")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new CustomSecurityFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class)
}
}
过滤逻辑
目前,我的自定义过滤器(一旦确认身份)只是对角色进行硬编码:
SimpleGrantedAuthority myrole = new SimpleGrantedAuthority("METADATA_CURATORZ")
return new PreAuthenticatedAuthenticationToken(securityUser, null, [myrole])
然后在重定向到所需的端点之前将该身份验证对象(上面返回)添加到我的 SecurityContext:
SecurityContextHolder.getContext().setAuthentication(authentication)
控制器端点
@RequestMapping(path = '/admin/test', method = GET, produces = 'text/plain')
String test(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication()
String roles = auth.getAuthorities()
return "roles: ${roles}"
}
这个端点然后在浏览器中产生一个响应:
“角色:[METADATA_CURATORZ]”
太好了。因此,我的身份验证和向我的用户应用角色运行良好。
现在,如果我从安全配置中取消注释此行:
//.antMatchers("/admin/test").hasRole("METADATA_CURATORZ")
我无法再访问该资源并收到 403 错误——即使我们已经证明角色已设置。
这对我来说似乎完全荒谬和破碎,但我不是 Spring Security 专家。
我可能遗漏了一些非常简单的东西。有什么想法吗?
我的一些问题:
- 是否需要将我的自定义过滤器放在特定的内置过滤器之前,以确保在执行该过滤器之后执行授权步骤?
- 在请求周期中何时进行 antMatcher/hasRole 检查?
- 我是否需要更改我在安全配置链中调用的顺序,以及我应该如何理解我当前编写的配置?它显然没有做我认为应该做的事情。
【问题讨论】:
-
这个问题你解决了吗?您能否分享使用 Spring Security 的自定义角色的分步指南。
标签: spring authentication spring-security filter authorization