Search in sources :

Example 16 with ErrorResponseException

use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.

the class PolicyService method create.

public Policy create(AbstractPolicyRepresentation representation) {
    PolicyStore policyStore = authorization.getStoreFactory().getPolicyStore();
    Policy existing = policyStore.findByName(representation.getName(), resourceServer.getId());
    if (existing != null) {
        throw new ErrorResponseException("Policy with name [" + representation.getName() + "] already exists", "Conflicting policy", Status.CONFLICT);
    }
    return policyStore.create(representation, resourceServer);
}
Also used : Policy(org.keycloak.authorization.model.Policy) PolicyStore(org.keycloak.authorization.store.PolicyStore) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 17 with ErrorResponseException

use of org.keycloak.services.ErrorResponseException 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 18 with ErrorResponseException

use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.

the class ProtectionService method getResourceServer.

private ResourceServer getResourceServer(KeycloakIdentity identity) {
    String clientId = identity.getAccessToken().getIssuedFor();
    RealmModel realm = authorization.getKeycloakSession().getContext().getRealm();
    ClientModel clientModel = realm.getClientByClientId(clientId);
    if (clientModel == null) {
        clientModel = realm.getClientById(clientId);
        if (clientModel == null) {
            throw new ErrorResponseException("invalid_clientId", "Client application with id [" + clientId + "] does not exist in realm [" + realm.getName() + "]", Status.BAD_REQUEST);
        }
    }
    ResourceServer resourceServer = this.authorization.getStoreFactory().getResourceServerStore().findByClient(clientModel);
    if (resourceServer == null) {
        throw new ErrorResponseException("invalid_clientId", "Client application [" + clientModel.getClientId() + "] is not registered as a resource server.", Status.FORBIDDEN);
    }
    return resourceServer;
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 19 with ErrorResponseException

use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.

the class ProtectionService method createIdentity.

private KeycloakIdentity createIdentity(boolean checkProtectionScope) {
    KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
    ResourceServer resourceServer = getResourceServer(identity);
    KeycloakSession keycloakSession = authorization.getKeycloakSession();
    RealmModel realm = keycloakSession.getContext().getRealm();
    ClientModel client = realm.getClientById(resourceServer.getId());
    if (checkProtectionScope) {
        if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_SCOPE, "Requires uma_protection scope.", Status.FORBIDDEN);
        }
    }
    return identity;
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) KeycloakSession(org.keycloak.models.KeycloakSession) ErrorResponseException(org.keycloak.services.ErrorResponseException) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 20 with ErrorResponseException

use of org.keycloak.services.ErrorResponseException in project keycloak by keycloak.

the class UserManagedPermissionService method checkRequest.

private void checkRequest(String resourceId, UmaPermissionRepresentation representation) {
    ResourceStore resourceStore = this.authorization.getStoreFactory().getResourceStore();
    Resource resource = resourceStore.findById(resourceId, resourceServer.getId());
    if (resource == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource [" + resourceId + "] cannot be found", Response.Status.BAD_REQUEST);
    }
    if (!resource.getOwner().equals(identity.getId())) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resource owner can access policies for resource [" + resourceId + "]", Status.BAD_REQUEST);
    }
    if (!resource.isOwnerManagedAccess()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resources with owner managed accessed can have policies", Status.BAD_REQUEST);
    }
    if (!resourceServer.isAllowRemoteResourceManagement()) {
        throw new ErrorResponseException(OAuthErrorException.REQUEST_NOT_SUPPORTED, "Remote Resource Management not enabled on resource server [" + resourceServer.getId() + "]", Status.FORBIDDEN);
    }
    if (representation != null) {
        Set<String> resourceScopes = resource.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
        Set<String> scopes = representation.getScopes();
        if (scopes == null || scopes.isEmpty()) {
            scopes = resourceScopes;
            representation.setScopes(scopes);
        }
        if (!resourceScopes.containsAll(scopes)) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST);
        }
        if (representation.getCondition() != null) {
            if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) {
                throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Script upload not supported", Status.BAD_REQUEST);
            }
        }
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) Profile(org.keycloak.common.Profile) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) OAuthErrorException(org.keycloak.OAuthErrorException) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Status(javax.ws.rs.core.Response.Status) Identity(org.keycloak.authorization.identity.Identity) DELETE(javax.ws.rs.DELETE) PolicyTypeResourceService(org.keycloak.authorization.admin.PolicyTypeResourceService) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) Set(java.util.Set) IOException(java.io.IOException) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) PermissionService(org.keycloak.authorization.admin.PermissionService) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) Response(javax.ws.rs.core.Response) NoCache(org.jboss.resteasy.annotations.cache.NoCache) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) PUT(javax.ws.rs.PUT) Resource(org.keycloak.authorization.model.Resource) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Aggregations

ErrorResponseException (org.keycloak.services.ErrorResponseException)60 Consumes (javax.ws.rs.Consumes)25 Path (javax.ws.rs.Path)20 POST (javax.ws.rs.POST)19 ClientModel (org.keycloak.models.ClientModel)19 Produces (javax.ws.rs.Produces)17 NoCache (org.jboss.resteasy.annotations.cache.NoCache)14 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)11 NotFoundException (javax.ws.rs.NotFoundException)9 IOException (java.io.IOException)8 Response (javax.ws.rs.core.Response)8 DELETE (javax.ws.rs.DELETE)7 PUT (javax.ws.rs.PUT)7 OAuthErrorException (org.keycloak.OAuthErrorException)7 RealmModel (org.keycloak.models.RealmModel)7 ModelException (org.keycloak.models.ModelException)6 RoleModel (org.keycloak.models.RoleModel)6 List (java.util.List)5 GET (javax.ws.rs.GET)5 Resource (org.keycloak.authorization.model.Resource)5