[keycloak-user] Keycloak fine grained permissions with Spring Boot / Spring Security

David Marsh dmarsh26 at outlook.com
Thu May 9 07:03:26 EDT 2019


Seems this is what i needed:


@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;
        }
    }


________________________________
From: keycloak-user-bounces at lists.jboss.org <keycloak-user-bounces at lists.jboss.org> on behalf of David Marsh <dmarsh26 at outlook.com>
Sent: 09 May 2019 08:45
To: keycloak-user at lists.jboss.org
Subject: [keycloak-user] Keycloak fine grained permissions with Spring Boot / Spring Security

I would like to use permissions or scopes or similar to allow fine grained access to REST resource.

Ideally I would like to do something like:


@PreAuthorize("hasPermission('Brands', 'brands:write')")

ResponseEntity<Brand> getBrand(@PathVariable("brandCode") String brandCode);

where 'Brands' is a keycloak client authorization resource with scopes 'brands:write, brands:read'.

The only annotation that seems to work is @Secured with a role, I do not with to do RBAC.

@Secured({"ROLE_STAFF"})

I have looked at the PolicyEnforcer, it is unclear to me exactly how it is supposed to be used.

I can write code of the form:


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

     // This works....
}

How can I tie the AuthorizationContext from PolicyEnforcing to the standard Spring security annotations ?

thanks
David
_______________________________________________
keycloak-user mailing list
keycloak-user at lists.jboss.org
https://lists.jboss.org/mailman/listinfo/keycloak-user


More information about the keycloak-user mailing list