我在使用Spring Security的Pre / Post Authorization Annotations和使用Keycloak集成的Servlet API时遇到了问题。我没有进一步的运气调查了很多文章,教程和以下问题:
我想要的只是删除ROLES_前缀,使用分层角色和一种舒适的方式来检索用户的角色。
截至目前,我能够在Controller中检索这样的分层角色,但不能使用注释:
@Controller
class HomeController {
@Autowired
AccessToken token
@GetMapping('/')
def home(Authentication auth, HttpServletRequest request) {
// Role 'admin' is defined in Keycloak for this application
assert token.getResourceAccess('my-app').roles == ['admin']
// All effective roles are mapped
assert auth.authorities.collect { it.authority }.containsAll(['admin', 'author', 'user'])
// (!) But this won't work:
assert request.isUserInRole('admin')
}
// (!) Leads to a 403: Forbidden
@GetMapping('/sec')
@PreAuthorize("hasRole('admin')") {
return "Hello World"
}
}
我猜测@PreAuthorize
注释不起作用,因为Servlet方法不成功。
Keycloak和Spring中只定义了三个角色 - 管理员,作者,用户:
enum Role {
USER('user'),
AUTHOR('author'),
ADMIN('admin')
final String id
Role(String id) {
this.id = id
}
@Override
String toString() {
id
}
}
Keycloak配置
从这个网络安全删除@EnableGlobalMethodSecurity
注释显示由Error creating bean with name 'resourceHandlerMapping'
错误引起的No ServletContext set
- 没有线索,来自哪里!
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
/**
* Registers the KeycloakAuthenticationProvider with the authentication manager.
*/
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider().tap { provider ->
// Assigns the Roles via Keycloaks role mapping
provider.grantedAuthoritiesMapper = userAuthoritiesMapper
})
}
@Bean
RoleHierarchyImpl getRoleHierarchy() {
new RoleHierarchyImpl().tap {
hierarchy = "$Role.ADMIN > $Role.AUTHOR > $Role.USER"
}
}
@Bean
GrantedAuthoritiesMapper getUserAuthoritiesMapper() {
new RoleHierarchyAuthoritiesMapper(roleHierarchy)
}
SecurityExpressionHandler<FilterInvocation> expressionHandler() {
// Removes the prefix
new DefaultWebSecurityExpressionHandler().tap {
roleHierarchy = roleHierarchy
defaultRolePrefix = null
}
}
// ...
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
AccessToken accessToken() {
def request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
def authToken = (KeycloakAuthenticationToken) request.userPrincipal
def securityContext = (KeycloakSecurityContext) authToken.credentials
return securityContext.token
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http)
http
.authorizeRequests()
.expressionHandler(expressionHandler())
// ...
}
}
全局方法安全配置
我需要明确允许allow-bean-definition-overriding
,因为否则我得到了bean with that name already defined
错误,这表明我完全失去了对整个情况的控制,并且不知道发生了什么。
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Autowired
RoleHierarchy roleHierarchy
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
((DefaultMethodSecurityExpressionHandler)super.createExpressionHandler()).tap {
roleHierarchy = roleHierarchy
defaultRolePrefix = null
}
}
}
任何进一步的配置可能很重要?非常感谢你的帮助!
正如M. Deinum指出的那样,必须用defaultRolePrefix
在多个地方移除BeanPostProcessor
,(docs.spring.io) Disable ROLE_ Prefixing对此进行了解释。
这种方法对我来说似乎不太干净,因此我编写了一个自定义AuthoritiesMapper
来实现Keycloak中的映射层次角色,而无需将它们重命名为ROLE_ Spring标准。首先,修改了Roles
枚举以符合应用范围内的标准:
enum Role {
USER('ROLE_USER'),
AUTHOR('ROLE_AUTHOR'),
ADMIN('ROLE_ADMIN')
// ...
}
其次,我用前缀层次化实现替换了RoleHierarchyAuthoritiesMapper
:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
// ..
// Replaces the RoleHierarchyAuthoritiesMapper
@Bean
GrantedAuthoritiesMapper getUserAuthoritiesMapper() {
new PrefixingRoleHierarchyAuthoritiesMapper(roleHierarchy)
}
}
class PrefixingRoleHierarchyAuthoritiesMapper extends RoleHierarchyAuthoritiesMapper {
String prefix = 'ROLE_'
PrefixingRoleHierarchyAuthoritiesMapper(RoleHierarchy roleHierarchy) {
super(roleHierarchy)
}
@Override
Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
def prefixedAuthorities = authorities.collect { GrantedAuthority originalAuthority ->
new GrantedAuthority() {
String authority = "${prefix}${originalAuthority.authority}".toUpperCase()
}
}
super.mapAuthorities(prefixedAuthorities)
}
}
最后,我摆脱了GlobalMethodSecurityConfig
。