使用Spring Boot / Spring Security的Keycloak细粒度权限

时间:2019-05-09 07:56:13

标签: spring security keycloak pep

我想使用权限或范围或类似权限来允许对REST资源的细粒度访问。

理想情况下,我想执行以下操作:

@PreAuthorize("hasPermission('Brands', 'brands:write')")
ResponseEntity<Brand> getBrand(@PathVariable("brandCode") String brandCode);

其中“品牌”是密钥范围客户端授权资源,范围为“ brands:write,brands:read”。

似乎唯一起作用的注释是@Secured角色,我不想执行RBAC。

@Secured({"ROLE_STAFF"})

我看过PolicyEnforcer,但我不清楚该如何使用它。

我可以编写以下形式的代码:

KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
AuthorizationContext authzContext = keycloakSecurityContext.getAuthorizationContext();
if (authzContext.hasScopePermission("brands:write")) {

// This works....
}

如何将PolicyEnforcing中的AuthorizationContext与标准的Spring安全注释联系起来?

1 个答案:

答案 0 :(得分:1)

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
@Autowired
private HttpServletRequest request;


@Override
public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
    if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)){
        return false;
    }

    KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    AuthorizationContext authzContext = keycloakSecurityContext.getAuthorizationContext();

    if(targetDomainObject instanceof String) {
        return authzContext.hasPermission((String)targetDomainObject, (String)permission);
    } else if(targetDomainObject == null) {
        return authzContext.hasScopePermission((String)permission);
    } else {
        return false;
    }
}