Search in sources :

Example 51 with ErrorResponseException

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

the class PolicyEvaluationService method evaluate.

@POST
@Consumes("application/json")
@Produces("application/json")
public Response evaluate(PolicyEvaluationRequest evaluationRequest) {
    this.auth.realm().requireViewAuthorization();
    CloseableKeycloakIdentity identity = createIdentity(evaluationRequest);
    try {
        AuthorizationRequest request = new AuthorizationRequest();
        Map<String, List<String>> claims = new HashMap<>();
        Map<String, String> givenAttributes = evaluationRequest.getContext().get("attributes");
        if (givenAttributes != null) {
            givenAttributes.forEach((key, entryValue) -> {
                if (entryValue != null) {
                    List<String> values = new ArrayList<>();
                    Collections.addAll(values, entryValue.split(","));
                    claims.put(key, values);
                }
            });
        }
        request.setClaims(claims);
        return Response.ok(PolicyEvaluationResponseBuilder.build(evaluate(evaluationRequest, createEvaluationContext(evaluationRequest, identity), request), resourceServer, authorization, identity)).build();
    } catch (Exception e) {
        logger.error("Error while evaluating permissions", e);
        throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Error while evaluating permissions.", Status.INTERNAL_SERVER_ERROR);
    } finally {
        identity.close();
    }
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ErrorResponseException(org.keycloak.services.ErrorResponseException) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 52 with ErrorResponseException

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

the class UserManagedPermissionService method update.

@Path("{policyId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Response update(@PathParam("policyId") String policyId, String payload) {
    UmaPermissionRepresentation representation;
    try {
        representation = JsonSerialization.readValue(payload, UmaPermissionRepresentation.class);
    } catch (IOException e) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to parse representation", Status.BAD_REQUEST);
    }
    checkRequest(getAssociatedResourceId(policyId), representation);
    return PolicyTypeResourceService.class.cast(delegate.getResource(policyId)).update(payload);
}
Also used : PolicyTypeResourceService(org.keycloak.authorization.admin.PolicyTypeResourceService) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Example 53 with ErrorResponseException

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

the class AbstractCibaEndpoint method authenticateClient.

protected ClientModel authenticateClient() {
    checkSsl();
    checkRealm();
    AuthorizeClientUtil.ClientAuthResult clientAuth = AuthorizeClientUtil.authorizeClient(session, event, null);
    ClientModel client = clientAuth.getClient();
    if (client.isBearerOnly()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_CLIENT, "Bearer-only not allowed", Response.Status.BAD_REQUEST);
    }
    if (!realm.getCibaPolicy().isOIDCCIBAGrantEnabled(client)) {
        event.error(Errors.NOT_ALLOWED);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Client not allowed OIDC CIBA Grant", Response.Status.BAD_REQUEST);
    }
    event.client(client);
    return client;
}
Also used : ClientModel(org.keycloak.models.ClientModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthorizeClientUtil(org.keycloak.protocol.oidc.utils.AuthorizeClientUtil)

Example 54 with ErrorResponseException

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

the class AbstractCibaEndpoint method checkSsl.

protected void checkSsl() {
    ClientConnection clientConnection = session.getContext().getContextObject(ClientConnection.class);
    RealmModel realm = session.getContext().getRealm();
    if (!session.getContext().getUri().getBaseUri().getScheme().equals("https") && realm.getSslRequired().isRequired(clientConnection)) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "HTTPS required", Response.Status.FORBIDDEN);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientConnection(org.keycloak.common.ClientConnection) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 55 with ErrorResponseException

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

the class BackchannelAuthenticationEndpoint method authorizeClient.

private CIBAAuthenticationRequest authorizeClient(MultivaluedMap<String, String> params) {
    ClientModel client = null;
    try {
        client = authenticateClient();
    } catch (WebApplicationException wae) {
        OAuth2ErrorRepresentation errorRep = (OAuth2ErrorRepresentation) wae.getResponse().getEntity();
        throw new ErrorResponseException(errorRep.getError(), errorRep.getErrorDescription(), Response.Status.UNAUTHORIZED);
    }
    BackchannelAuthenticationEndpointRequest endpointRequest = BackchannelAuthenticationEndpointRequestParserProcessor.parseRequest(event, session, client, params, realm.getCibaPolicy());
    UserModel user = resolveUser(endpointRequest, realm.getCibaPolicy().getAuthRequestedUserHint());
    CIBAAuthenticationRequest request = new CIBAAuthenticationRequest(session, user, client);
    request.setClient(client);
    String scope = endpointRequest.getScope();
    if (scope == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "missing parameter : scope", Response.Status.BAD_REQUEST);
    }
    request.setScope(scope);
    // optional parameters
    if (endpointRequest.getBindingMessage() != null) {
        validateBindingMessage(endpointRequest.getBindingMessage());
        request.setBindingMessage(endpointRequest.getBindingMessage());
    }
    if (endpointRequest.getAcr() != null)
        request.setAcrValues(endpointRequest.getAcr());
    CibaConfig policy = realm.getCibaPolicy();
    // create JWE encoded auth_req_id from Auth Req ID.
    Integer expiresIn = Optional.ofNullable(endpointRequest.getRequestedExpiry()).orElse(policy.getExpiresIn());
    request.exp(request.getIat() + expiresIn.longValue());
    StringBuilder scopes = new StringBuilder(Optional.ofNullable(request.getScope()).orElse(""));
    client.getClientScopes(true).forEach((key, value) -> {
        if (value.isDisplayOnConsentScreen())
            scopes.append(" ").append(value.getName());
    });
    request.setScope(scopes.toString());
    if (endpointRequest.getClientNotificationToken() != null) {
        if (!policy.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token supported only for the ping mode", Response.Status.BAD_REQUEST);
        }
        if (endpointRequest.getClientNotificationToken().length() > 1024) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token length is limited to 1024 characters", Response.Status.BAD_REQUEST);
        }
        request.setClientNotificationToken(endpointRequest.getClientNotificationToken());
    }
    if (endpointRequest.getClientNotificationToken() == null && policy.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token needs to be provided with the ping mode", Response.Status.BAD_REQUEST);
    }
    if (endpointRequest.getUserCode() != null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "User code not supported", Response.Status.BAD_REQUEST);
    }
    extractAdditionalParams(endpointRequest, request);
    try {
        session.clientPolicy().triggerOnEvent(new BackchannelAuthenticationRequestContext(endpointRequest, request, params));
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
    return request;
}
Also used : BackchannelAuthenticationRequestContext(org.keycloak.protocol.oidc.grants.ciba.clientpolicy.context.BackchannelAuthenticationRequestContext) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) CIBAAuthenticationRequest(org.keycloak.protocol.oidc.grants.ciba.channel.CIBAAuthenticationRequest) BackchannelAuthenticationEndpointRequest(org.keycloak.protocol.oidc.grants.ciba.endpoints.request.BackchannelAuthenticationEndpointRequest) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) CibaConfig(org.keycloak.models.CibaConfig) 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