Search in sources :

Example 6 with EvaluationContext

use of org.keycloak.authorization.policy.evaluation.EvaluationContext in project keycloak by keycloak.

the class PolicyEvaluationService method createPermissions.

private List<ResourcePermission> createPermissions(PolicyEvaluationRequest representation, EvaluationContext evaluationContext, AuthorizationProvider authorization, AuthorizationRequest request) {
    return representation.getResources().stream().flatMap((Function<ResourceRepresentation, Stream<ResourcePermission>>) resource -> {
        StoreFactory storeFactory = authorization.getStoreFactory();
        if (resource == null) {
            resource = new ResourceRepresentation();
        }
        Set<ScopeRepresentation> givenScopes = resource.getScopes();
        if (givenScopes == null) {
            givenScopes = new HashSet<>();
        }
        ScopeStore scopeStore = storeFactory.getScopeStore();
        Set<Scope> scopes = givenScopes.stream().map(scopeRepresentation -> scopeStore.findByName(scopeRepresentation.getName(), resourceServer.getId())).collect(Collectors.toSet());
        if (resource.getId() != null) {
            Resource resourceModel = storeFactory.getResourceStore().findById(resource.getId(), resourceServer.getId());
            return new ArrayList<>(Arrays.asList(Permissions.createResourcePermissions(resourceModel, resourceServer, scopes, authorization, request))).stream();
        } else if (resource.getType() != null) {
            return storeFactory.getResourceStore().findByType(resource.getType(), resourceServer.getId()).stream().map(resource1 -> Permissions.createResourcePermissions(resource1, resourceServer, scopes, authorization, request));
        } else {
            if (scopes.isEmpty()) {
                return Stream.empty();
            }
            List<Resource> resources = storeFactory.getResourceStore().findByScope(scopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId());
            if (resources.isEmpty()) {
                return scopes.stream().map(scope -> new ResourcePermission(null, new ArrayList<>(Arrays.asList(scope)), resourceServer));
            }
            return resources.stream().map(resource12 -> Permissions.createResourcePermissions(resource12, resourceServer, scopes, authorization, request));
        }
    }).collect(Collectors.toList());
}
Also used : ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Produces(javax.ws.rs.Produces) Permissions(org.keycloak.authorization.permission.Permissions) OAuthErrorException(org.keycloak.OAuthErrorException) Consumes(javax.ws.rs.Consumes) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AccessToken(org.keycloak.representations.AccessToken) DecisionPermissionCollector(org.keycloak.authorization.policy.evaluation.DecisionPermissionCollector) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) PolicyEvaluationResponseBuilder(org.keycloak.authorization.admin.representation.PolicyEvaluationResponseBuilder) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) List(java.util.List) ScopeStore(org.keycloak.authorization.store.ScopeStore) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) Attributes(org.keycloak.authorization.attribute.Attributes) Permission(org.keycloak.representations.idm.authorization.Permission) Logger(org.jboss.logging.Logger) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) TokenManager(org.keycloak.protocol.oidc.TokenManager) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PolicyEvaluationRequest(org.keycloak.representations.idm.authorization.PolicyEvaluationRequest) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) Status(javax.ws.rs.core.Response.Status) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) Result(org.keycloak.authorization.policy.evaluation.Result) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) Resource(org.keycloak.authorization.model.Resource) ScopeStore(org.keycloak.authorization.store.ScopeStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Function(java.util.function.Function) Scope(org.keycloak.authorization.model.Scope) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) List(java.util.List) ArrayList(java.util.ArrayList) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 7 with EvaluationContext

use of org.keycloak.authorization.policy.evaluation.EvaluationContext in project keycloak by keycloak.

the class AuthorizationTokenService method authorize.

public Response authorize(KeycloakAuthorizationRequest request) {
    EventBuilder event = request.getEvent();
    // it is not secure to allow public clients to push arbitrary claims because message can be tampered
    if (isPublicClientRequestingEntitlementWithClaims(request)) {
        CorsErrorResponseException forbiddenClientException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_GRANT, "Public clients are not allowed to send claims", Status.FORBIDDEN);
        fireErrorEvent(event, Errors.INVALID_REQUEST, forbiddenClientException);
        throw forbiddenClientException;
    }
    try {
        PermissionTicketToken ticket = getPermissionTicket(request);
        request.setClaims(ticket.getClaims());
        EvaluationContext evaluationContext = createEvaluationContext(request);
        KeycloakIdentity identity = KeycloakIdentity.class.cast(evaluationContext.getIdentity());
        if (identity != null) {
            event.user(identity.getId());
        }
        ResourceServer resourceServer = getResourceServer(ticket, request);
        Collection<Permission> permissions;
        if (request.getTicket() != null) {
            permissions = evaluateUserManagedPermissions(request, ticket, resourceServer, evaluationContext);
        } else if (ticket.getPermissions().isEmpty() && request.getRpt() == null) {
            permissions = evaluateAllPermissions(request, resourceServer, evaluationContext);
        } else {
            permissions = evaluatePermissions(request, ticket, resourceServer, evaluationContext, identity);
        }
        if (isGranted(ticket, request, permissions)) {
            AuthorizationProvider authorization = request.getAuthorization();
            ClientModel targetClient = authorization.getRealm().getClientById(resourceServer.getId());
            Metadata metadata = request.getMetadata();
            String responseMode = metadata != null ? metadata.getResponseMode() : null;
            if (responseMode != null) {
                if (RESPONSE_MODE_DECISION.equals(metadata.getResponseMode())) {
                    Map<String, Object> responseClaims = new HashMap<>();
                    responseClaims.put(RESPONSE_MODE_DECISION_RESULT, true);
                    return createSuccessfulResponse(responseClaims, request);
                } else if (RESPONSE_MODE_PERMISSIONS.equals(metadata.getResponseMode())) {
                    return createSuccessfulResponse(permissions, request);
                } else {
                    CorsErrorResponseException invalidResponseModeException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.INVALID_REQUEST, "Invalid response_mode", Status.BAD_REQUEST);
                    fireErrorEvent(event, Errors.INVALID_REQUEST, invalidResponseModeException);
                    throw invalidResponseModeException;
                }
            } else {
                return createSuccessfulResponse(createAuthorizationResponse(identity, permissions, request, targetClient), request);
            }
        }
        if (request.isSubmitRequest()) {
            CorsErrorResponseException submittedRequestException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.ACCESS_DENIED, "request_submitted", Status.FORBIDDEN);
            fireErrorEvent(event, Errors.ACCESS_DENIED, submittedRequestException);
            throw submittedRequestException;
        } else {
            CorsErrorResponseException notAuthorizedException = new CorsErrorResponseException(request.getCors(), OAuthErrorException.ACCESS_DENIED, "not_authorized", Status.FORBIDDEN);
            fireErrorEvent(event, Errors.ACCESS_DENIED, notAuthorizedException);
            throw notAuthorizedException;
        }
    } catch (ErrorResponseException | CorsErrorResponseException cause) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error while evaluating permissions", cause);
        }
        throw cause;
    } catch (Exception cause) {
        logger.error("Unexpected error while evaluating permissions", cause);
        throw new CorsErrorResponseException(request.getCors(), OAuthErrorException.SERVER_ERROR, "Unexpected error while evaluating permissions", Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) ClientModel(org.keycloak.models.ClientModel) EventBuilder(org.keycloak.events.EventBuilder) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) ErrorResponseException(org.keycloak.services.ErrorResponseException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 8 with EvaluationContext

use of org.keycloak.authorization.policy.evaluation.EvaluationContext in project keycloak by keycloak.

the class ClientPolicyProvider method evaluate.

@Override
public void evaluate(Evaluation evaluation) {
    ClientPolicyRepresentation representation = representationFunction.apply(evaluation.getPolicy(), evaluation.getAuthorizationProvider());
    AuthorizationProvider authorizationProvider = evaluation.getAuthorizationProvider();
    RealmModel realm = authorizationProvider.getKeycloakSession().getContext().getRealm();
    EvaluationContext context = evaluation.getContext();
    for (String client : representation.getClients()) {
        ClientModel clientModel = realm.getClientById(client);
        if (context.getAttributes().containsValue("kc.client.id", clientModel.getClientId())) {
            evaluation.grant();
            return;
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) ClientModel(org.keycloak.models.ClientModel) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext)

Example 9 with EvaluationContext

use of org.keycloak.authorization.policy.evaluation.EvaluationContext 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)

Aggregations

EvaluationContext (org.keycloak.authorization.policy.evaluation.EvaluationContext)9 DefaultEvaluationContext (org.keycloak.authorization.common.DefaultEvaluationContext)6 Collection (java.util.Collection)4 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)4 ResourceServer (org.keycloak.authorization.model.ResourceServer)4 ClientModelIdentity (org.keycloak.authorization.common.ClientModelIdentity)3 Policy (org.keycloak.authorization.model.Policy)3 Resource (org.keycloak.authorization.model.Resource)3 Scope (org.keycloak.authorization.model.Scope)3 ClientModel (org.keycloak.models.ClientModel)3 HashMap (java.util.HashMap)2 OAuthErrorException (org.keycloak.OAuthErrorException)2 Attributes (org.keycloak.authorization.attribute.Attributes)2 KeycloakIdentity (org.keycloak.authorization.common.KeycloakIdentity)2 ResourcePermission (org.keycloak.authorization.permission.ResourcePermission)2 Permission (org.keycloak.representations.idm.authorization.Permission)2 ErrorResponseException (org.keycloak.services.ErrorResponseException)2 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1