Search in sources :

Example 21 with ErrorResponseException

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

the class AbstractOAuth2IdentityProvider method validateExternalTokenThroughUserInfo.

protected BrokeredIdentityContext validateExternalTokenThroughUserInfo(EventBuilder event, String subjectToken, String subjectTokenType) {
    event.detail("validation_method", "user info");
    SimpleHttp.Response response = null;
    int status = 0;
    try {
        String userInfoUrl = getProfileEndpointForValidation(event);
        response = buildUserInfoRequest(subjectToken, userInfoUrl).asResponse();
        status = response.getStatus();
    } catch (IOException e) {
        logger.debug("Failed to invoke user info for external exchange", e);
    }
    if (status != 200) {
        logger.debug("Failed to invoke user info status: " + status);
        event.detail(Details.REASON, "user info call failure");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    JsonNode profile = null;
    try {
        profile = response.asJson();
    } catch (IOException e) {
        event.detail(Details.REASON, "user info call failure");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    BrokeredIdentityContext context = extractIdentityFromProfile(event, profile);
    if (context.getId() == null) {
        event.detail(Details.REASON, "user info call failure");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    return context;
}
Also used : SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) ErrorResponseException(org.keycloak.services.ErrorResponseException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) AuthorizationEndpoint(org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Example 22 with ErrorResponseException

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

the class OIDCIdentityProvider method validateJwt.

protected final BrokeredIdentityContext validateJwt(EventBuilder event, String subjectToken, String subjectTokenType) {
    if (!getConfig().isValidateSignature()) {
        return validateExternalTokenThroughUserInfo(event, subjectToken, subjectTokenType);
    }
    event.detail("validation_method", "signature");
    if (getConfig().isUseJwksUrl()) {
        if (getConfig().getJwksUrl() == null) {
            event.detail(Details.REASON, "jwks url unset");
            event.error(Errors.INVALID_CONFIG);
            throw new ErrorResponseException(Errors.INVALID_CONFIG, "Invalid server config", Response.Status.BAD_REQUEST);
        }
    } else if (getConfig().getPublicKeySignatureVerifier() == null) {
        event.detail(Details.REASON, "public key unset");
        event.error(Errors.INVALID_CONFIG);
        throw new ErrorResponseException(Errors.INVALID_CONFIG, "Invalid server config", Response.Status.BAD_REQUEST);
    }
    JsonWebToken parsedToken = null;
    try {
        parsedToken = validateToken(subjectToken, true);
    } catch (IdentityBrokerException e) {
        logger.debug("Unable to validate token for exchange", e);
        event.detail(Details.REASON, "token validation failure");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    try {
        boolean idTokenType = OAuth2Constants.ID_TOKEN_TYPE.equals(subjectTokenType);
        BrokeredIdentityContext context = extractIdentity(null, idTokenType ? null : subjectToken, parsedToken);
        if (context == null) {
            event.detail(Details.REASON, "Failed to extract identity from token");
            event.error(Errors.INVALID_TOKEN);
            throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
        }
        if (idTokenType) {
            context.getContextData().put(VALIDATED_ID_TOKEN, subjectToken);
        } else {
            context.getContextData().put(KeycloakOIDCIdentityProvider.VALIDATED_ACCESS_TOKEN, parsedToken);
        }
        context.getContextData().put(EXCHANGE_PROVIDER, getConfig().getAlias());
        context.setIdp(this);
        context.setIdpConfig(getConfig());
        return context;
    } catch (IOException e) {
        logger.debug("Unable to extract identity from identity token", e);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException) JsonWebToken(org.keycloak.representations.JsonWebToken) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Example 23 with ErrorResponseException

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

the class OIDCIdentityProvider method exchangeExternalImpl.

@Override
protected BrokeredIdentityContext exchangeExternalImpl(EventBuilder event, MultivaluedMap<String, String> params) {
    if (!supportsExternalExchange())
        return null;
    String subjectToken = params.getFirst(OAuth2Constants.SUBJECT_TOKEN);
    if (subjectToken == null) {
        event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN + " param unset");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "token not set", Response.Status.BAD_REQUEST);
    }
    String subjectTokenType = params.getFirst(OAuth2Constants.SUBJECT_TOKEN_TYPE);
    if (subjectTokenType == null) {
        subjectTokenType = OAuth2Constants.ACCESS_TOKEN_TYPE;
    }
    if (OAuth2Constants.JWT_TOKEN_TYPE.equals(subjectTokenType) || OAuth2Constants.ID_TOKEN_TYPE.equals(subjectTokenType)) {
        return validateJwt(event, subjectToken, subjectTokenType);
    } else if (OAuth2Constants.ACCESS_TOKEN_TYPE.equals(subjectTokenType)) {
        return validateExternalTokenThroughUserInfo(event, subjectToken, subjectTokenType);
    } else {
        event.detail(Details.REASON, OAuth2Constants.SUBJECT_TOKEN_TYPE + " invalid");
        event.error(Errors.INVALID_TOKEN_TYPE);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token type", Response.Status.BAD_REQUEST);
    }
}
Also used : ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 24 with ErrorResponseException

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

the class OIDCIdentityProvider method preprocessFederatedIdentity.

@Override
public void preprocessFederatedIdentity(KeycloakSession session, RealmModel realm, BrokeredIdentityContext context) {
    AuthenticationSessionModel authenticationSession = session.getContext().getAuthenticationSession();
    if (authenticationSession == null) {
        // no interacting with the brokered OP, likely doing token exchanges
        return;
    }
    String nonce = (String) context.getContextData().get(BROKER_NONCE_PARAM);
    if (nonce == null) {
        throw new IdentityBrokerException("OpenID Provider [" + getConfig().getProviderId() + "] did not return a nonce");
    }
    String expectedNonce = authenticationSession.getClientNote(BROKER_NONCE_PARAM);
    if (!nonce.equals(expectedNonce)) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid nonce", Response.Status.BAD_REQUEST);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 25 with ErrorResponseException

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

the class AbstractPermissionService method verifyRequestedScopes.

private Set<String> verifyRequestedScopes(PermissionRequest request, Resource resource) {
    Set<String> requestScopes = request.getScopes();
    if (requestScopes == null) {
        return Collections.emptySet();
    }
    ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
    return requestScopes.stream().map(scopeName -> {
        Scope scope = null;
        if (resource != null) {
            scope = resource.getScopes().stream().filter(scope1 -> scope1.getName().equals(scopeName)).findFirst().orElse(null);
            if (scope == null && resource.getType() != null) {
                scope = resourceStore.findByType(resource.getType(), resourceServer.getId()).stream().filter(baseResource -> baseResource.getOwner().equals(resource.getResourceServer())).flatMap(resource1 -> resource1.getScopes().stream()).filter(baseScope -> baseScope.getName().equals(scopeName)).findFirst().orElse(null);
            }
        } else {
            scope = authorization.getStoreFactory().getScopeStore().findByName(scopeName, resourceServer.getId());
        }
        if (scope == null) {
            throw new ErrorResponseException("invalid_scope", "Scope [" + scopeName + "] is invalid", Response.Status.BAD_REQUEST);
        }
        return scope.getName();
    }).collect(Collectors.toSet());
}
Also used : ResourceServer(org.keycloak.authorization.model.ResourceServer) Scope(org.keycloak.authorization.model.Scope) Permission(org.keycloak.representations.idm.authorization.Permission) Set(java.util.Set) HashMap(java.util.HashMap) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) ArrayList(java.util.ArrayList) List(java.util.List) Response(javax.ws.rs.core.Response) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) Urls(org.keycloak.services.Urls) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) Scope(org.keycloak.authorization.model.Scope) 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