Search in sources :

Example 46 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class PolicyEvaluationResponseBuilder method toRepresentation.

private static PolicyEvaluationResponse.PolicyResultRepresentation toRepresentation(Result.PolicyResult result, AuthorizationProvider authorization) {
    PolicyEvaluationResponse.PolicyResultRepresentation policyResultRep = new PolicyEvaluationResponse.PolicyResultRepresentation();
    PolicyRepresentation representation = new PolicyRepresentation();
    Policy policy = result.getPolicy();
    representation.setId(policy.getId());
    representation.setName(policy.getName());
    representation.setType(policy.getType());
    representation.setDecisionStrategy(policy.getDecisionStrategy());
    representation.setDescription(policy.getDescription());
    if ("uma".equals(representation.getType())) {
        Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
        filters.put(PermissionTicket.FilterOption.POLICY_ID, policy.getId());
        List<PermissionTicket> tickets = authorization.getStoreFactory().getPermissionTicketStore().find(filters, policy.getResourceServer().getId(), -1, 1);
        if (!tickets.isEmpty()) {
            KeycloakSession keycloakSession = authorization.getKeycloakSession();
            RealmModel realm = authorization.getRealm();
            PermissionTicket ticket = tickets.get(0);
            UserModel userOwner = keycloakSession.users().getUserById(realm, ticket.getOwner());
            UserModel requester = keycloakSession.users().getUserById(realm, ticket.getRequester());
            String resourceOwner;
            if (userOwner != null) {
                resourceOwner = getUserEmailOrUserName(userOwner);
            } else {
                ClientModel clientOwner = realm.getClientById(ticket.getOwner());
                resourceOwner = clientOwner.getClientId();
            }
            representation.setDescription("Resource owner (" + resourceOwner + ") grants access to " + getUserEmailOrUserName(requester));
        } else {
            String description = representation.getDescription();
            if (description != null) {
                representation.setDescription(description + " (User-Managed Policy)");
            } else {
                representation.setDescription("User-Managed Policy");
            }
        }
    }
    representation.setResources(policy.getResources().stream().map(resource -> resource.getName()).collect(Collectors.toSet()));
    Set<String> scopeNames = policy.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
    representation.setScopes(scopeNames);
    policyResultRep.setPolicy(representation);
    if (result.getEffect() == Decision.Effect.DENY) {
        policyResultRep.setStatus(DecisionEffect.DENY);
        policyResultRep.setScopes(representation.getScopes());
    } else {
        policyResultRep.setStatus(DecisionEffect.PERMIT);
    }
    policyResultRep.setAssociatedPolicies(result.getAssociatedPolicies().stream().map(policy1 -> toRepresentation(policy1, authorization)).collect(Collectors.toList()));
    return policyResultRep;
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ArrayList(java.util.ArrayList) PolicyEvaluationService(org.keycloak.authorization.admin.PolicyEvaluationService) UserModel(org.keycloak.models.UserModel) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Stream(java.util.stream.Stream) Result(org.keycloak.authorization.policy.evaluation.Result) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) DecisionEffect(org.keycloak.representations.idm.authorization.DecisionEffect) Comparator(java.util.Comparator) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) KeycloakSession(org.keycloak.models.KeycloakSession) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) EnumMap(java.util.EnumMap)

Example 47 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class AuthorizationTokenService method resolveResourcePermission.

private void resolveResourcePermission(KeycloakAuthorizationRequest request, ResourceServer resourceServer, KeycloakIdentity identity, AuthorizationProvider authorization, StoreFactory storeFactory, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, AtomicInteger limit, Permission permission, Set<Scope> requestedScopesModel, String resourceId) {
    Resource resource;
    if (resourceId.indexOf('-') != -1) {
        resource = resourceStore.findById(resourceId, resourceServer.getId());
    } else {
        resource = null;
    }
    if (resource != null) {
        addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource);
    } else if (resourceId.startsWith("resource-type:")) {
        // only resource types, no resource instances. resource types are owned by the resource server
        String resourceType = resourceId.substring("resource-type:".length());
        resourceStore.findByType(resourceType, resourceServer.getId(), resourceServer.getId(), resource1 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource1));
    } else if (resourceId.startsWith("resource-type-any:")) {
        // any resource with a given type
        String resourceType = resourceId.substring("resource-type-any:".length());
        resourceStore.findByType(resourceType, null, resourceServer.getId(), resource12 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource12));
    } else if (resourceId.startsWith("resource-type-instance:")) {
        // only resource instances with a given type
        String resourceType = resourceId.substring("resource-type-instance:".length());
        resourceStore.findByTypeInstance(resourceType, resourceServer.getId(), resource13 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource13));
    } else if (resourceId.startsWith("resource-type-owner:")) {
        // only resources where the current identity is the owner
        String resourceType = resourceId.substring("resource-type-owner:".length());
        resourceStore.findByType(resourceType, identity.getId(), resourceServer.getId(), resource14 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource14));
    } else {
        Resource ownerResource = resourceStore.findByName(resourceId, identity.getId(), resourceServer.getId());
        if (ownerResource != null) {
            permission.setResourceId(ownerResource.getId());
            addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, ownerResource);
        }
        if (!identity.isResourceServer() || !identity.getId().equals(resourceServer.getId())) {
            List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(resourceId, identity.getId(), resourceServer.getId());
            if (!tickets.isEmpty()) {
                List<Scope> scopes = new ArrayList<>();
                Resource grantedResource = null;
                for (PermissionTicket permissionTicket : tickets) {
                    if (grantedResource == null) {
                        grantedResource = permissionTicket.getResource();
                    }
                    scopes.add(permissionTicket.getScope());
                }
                requestedScopesModel.retainAll(scopes);
                ResourcePermission resourcePermission = addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, grantedResource);
                // the permission is explicitly granted by the owner, mark this permission as granted so that we don't run the evaluation engine on it
                resourcePermission.setGranted(true);
            }
            Resource serverResource = resourceStore.findByName(resourceId, resourceServer.getId());
            if (serverResource != null) {
                permission.setResourceId(serverResource.getId());
                addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, serverResource);
            }
        }
    }
    if (permissionsToEvaluate.isEmpty()) {
        CorsErrorResponseException invalidResourceException = new CorsErrorResponseException(request.getCors(), "invalid_resource", "Resource with id [" + resourceId + "] does not exist.", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, invalidResourceException);
        throw invalidResourceException;
    }
}
Also used : ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Arrays(java.util.Arrays) Tokens(org.keycloak.authorization.util.Tokens) UserSessionProvider(org.keycloak.models.UserSessionProvider) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) BiFunction(java.util.function.BiFunction) Permissions(org.keycloak.authorization.permission.Permissions) PermissionTicketAwareDecisionResultCollector(org.keycloak.authorization.policy.evaluation.PermissionTicketAwareDecisionResultCollector) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) MediaType(javax.ws.rs.core.MediaType) OAuthErrorException(org.keycloak.OAuthErrorException) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) ResourceStore(org.keycloak.authorization.store.ResourceStore) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) Collectors(java.util.stream.Collectors) IDToken(org.keycloak.representations.IDToken) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Objects(java.util.Objects) List(java.util.List) ScopeStore(org.keycloak.authorization.store.ScopeStore) ServiceAccountConstants(org.keycloak.common.constants.ServiceAccountConstants) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) Entry(java.util.Map.Entry) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Permission(org.keycloak.representations.idm.authorization.Permission) Logger(org.jboss.logging.Logger) StoreFactory(org.keycloak.authorization.store.StoreFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) RefreshToken(org.keycloak.representations.RefreshToken) TokenManager(org.keycloak.protocol.oidc.TokenManager) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) EventBuilder(org.keycloak.events.EventBuilder) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) Cors(org.keycloak.services.resources.Cors) Status(javax.ws.rs.core.Response.Status) Base64Url(org.keycloak.common.util.Base64Url) ResourceServer(org.keycloak.authorization.model.ResourceServer) Errors(org.keycloak.events.Errors) Authorization(org.keycloak.representations.AccessToken.Authorization) KeycloakSession(org.keycloak.models.KeycloakSession) HttpRequest(org.jboss.resteasy.spi.HttpRequest) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) JsonSerialization(org.keycloak.util.JsonSerialization) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) Urls(org.keycloak.services.Urls) AccessTokenResponseBuilder(org.keycloak.protocol.oidc.TokenManager.AccessTokenResponseBuilder) Resource(org.keycloak.authorization.model.Resource) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) Scope(org.keycloak.authorization.model.Scope) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 48 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class AuthorizationTokenService method getResourceServer.

private ResourceServer getResourceServer(PermissionTicketToken ticket, KeycloakAuthorizationRequest request) {
    AuthorizationProvider authorization = request.getAuthorization();
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServerStore resourceServerStore = storeFactory.getResourceServerStore();
    String issuedFor = ticket.getIssuedFor();
    if (issuedFor == null) {
        CorsErrorResponseException missingIssuedForException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "You must provide the issuedFor", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, missingIssuedForException);
        throw missingIssuedForException;
    }
    ClientModel clientModel = request.getRealm().getClientByClientId(issuedFor);
    if (clientModel == null) {
        CorsErrorResponseException unknownServerIdException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "Unknown resource server id: [" + issuedFor + "]", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, unknownServerIdException);
        throw unknownServerIdException;
    }
    ResourceServer resourceServer = resourceServerStore.findByClient(clientModel);
    if (resourceServer == null) {
        CorsErrorResponseException unsupportedPermissionsException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "Client does not support permissions", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, unsupportedPermissionsException);
        throw unsupportedPermissionsException;
    }
    return resourceServer;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 49 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class AuthorizationTokenService method createEvaluationContext.

private EvaluationContext createEvaluationContext(KeycloakAuthorizationRequest request) {
    String claimTokenFormat = request.getClaimTokenFormat();
    if (claimTokenFormat == null) {
        claimTokenFormat = CLAIM_TOKEN_FORMAT_JWT;
    }
    BiFunction<KeycloakAuthorizationRequest, AuthorizationProvider, EvaluationContext> evaluationContextProvider = SUPPORTED_CLAIM_TOKEN_FORMATS.get(claimTokenFormat);
    if (evaluationContextProvider == null) {
        CorsErrorResponseException unsupportedClaimTokenFormatException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "Claim token format [" + claimTokenFormat + "] not supported", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, unsupportedClaimTokenFormatException);
        throw unsupportedClaimTokenFormatException;
    }
    return evaluationContextProvider.apply(request, request.getAuthorization());
}
Also used : AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException)

Example 50 with AuthorizationProvider

use of org.keycloak.authorization.AuthorizationProvider in project keycloak by keycloak.

the class PolicyEvaluationTest method testCheckUserGroups.

public static void testCheckUserGroups(KeycloakSession session) {
    session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
    JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
    policyRepresentation.setName("testCheckUserGroups");
    StringBuilder builder = new StringBuilder();
    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var groups = realm.getUserGroups('jdoe');");
    builder.append("if (groups.size() == 2 && groups.contains('/Group A/Group B') && groups.contains('/Group A/Group D')) { $evaluation.grant(); }");
    policyRepresentation.setCode(builder.toString());
    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());
    DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
    provider.evaluate(evaluation);
    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientModel(org.keycloak.models.ClientModel) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer) DefaultEvaluation(org.keycloak.authorization.policy.evaluation.DefaultEvaluation)

Aggregations

AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)60 Policy (org.keycloak.authorization.model.Policy)35 ClientModel (org.keycloak.models.ClientModel)35 ResourceServer (org.keycloak.authorization.model.ResourceServer)30 StoreFactory (org.keycloak.authorization.store.StoreFactory)24 RealmModel (org.keycloak.models.RealmModel)23 HashMap (java.util.HashMap)18 UserModel (org.keycloak.models.UserModel)18 Resource (org.keycloak.authorization.model.Resource)16 PolicyProvider (org.keycloak.authorization.policy.provider.PolicyProvider)15 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 Scope (org.keycloak.authorization.model.Scope)13 List (java.util.List)12 DefaultEvaluation (org.keycloak.authorization.policy.evaluation.DefaultEvaluation)12 KeycloakSession (org.keycloak.models.KeycloakSession)12 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)11 Set (java.util.Set)10 Collectors (java.util.stream.Collectors)10 HashSet (java.util.HashSet)9