Search in sources :

Example 56 with ErrorResponseException

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

the class BackchannelAuthenticationEndpoint method processGrantRequest.

@POST
@NoCache
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response processGrantRequest(@Context HttpRequest httpRequest) {
    CIBAAuthenticationRequest request = authorizeClient(httpRequest.getDecodedFormParameters());
    try {
        String authReqId = request.serialize(session);
        AuthenticationChannelProvider provider = session.getProvider(AuthenticationChannelProvider.class);
        if (provider == null) {
            throw new RuntimeException("Authentication Channel Provider not found.");
        }
        CIBALoginUserResolver resolver = session.getProvider(CIBALoginUserResolver.class);
        if (resolver == null) {
            throw new RuntimeException("CIBA Login User Resolver not setup properly.");
        }
        UserModel user = request.getUser();
        String infoUsedByAuthentication = resolver.getInfoUsedByAuthentication(user);
        if (provider.requestAuthentication(request, infoUsedByAuthentication)) {
            CibaConfig cibaPolicy = realm.getCibaPolicy();
            int poolingInterval = cibaPolicy.getPoolingInterval();
            storeAuthenticationRequest(request, cibaPolicy, authReqId);
            ObjectNode response = JsonSerialization.createObjectNode();
            response.put(CibaGrantType.AUTH_REQ_ID, authReqId).put(OAuth2Constants.EXPIRES_IN, cibaPolicy.getExpiresIn());
            if (poolingInterval > 0) {
                response.put(OAuth2Constants.INTERVAL, poolingInterval);
            }
            return Response.ok(JsonSerialization.writeValueAsBytes(response)).build();
        }
    } catch (Exception e) {
        throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Failed to send authentication request", Response.Status.SERVICE_UNAVAILABLE);
    }
    throw new ErrorResponseException(OAuthErrorException.SERVER_ERROR, "Unexpected response from authentication device", Response.Status.SERVICE_UNAVAILABLE);
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationChannelProvider(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelProvider) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CIBALoginUserResolver(org.keycloak.protocol.oidc.grants.ciba.resolvers.CIBALoginUserResolver) CibaConfig(org.keycloak.models.CibaConfig) ErrorResponseException(org.keycloak.services.ErrorResponseException) CIBAAuthenticationRequest(org.keycloak.protocol.oidc.grants.ciba.channel.CIBAAuthenticationRequest) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) WebApplicationException(javax.ws.rs.WebApplicationException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 57 with ErrorResponseException

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

the class BackchannelAuthenticationEndpoint method resolveUser.

private UserModel resolveUser(BackchannelAuthenticationEndpointRequest endpointRequest, String authRequestedUserHint) {
    CIBALoginUserResolver resolver = session.getProvider(CIBALoginUserResolver.class);
    if (resolver == null) {
        throw new RuntimeException("CIBA Login User Resolver not setup properly.");
    }
    String userHint;
    UserModel user;
    if (authRequestedUserHint.equals(LOGIN_HINT_PARAM)) {
        userHint = endpointRequest.getLoginHint();
        if (userHint == null)
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "missing parameter : login_hint", Response.Status.BAD_REQUEST);
        user = resolver.getUserFromLoginHint(userHint);
    } else if (authRequestedUserHint.equals(ID_TOKEN_HINT)) {
        userHint = endpointRequest.getIdTokenHint();
        if (userHint == null)
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "missing parameter : id_token_hint", Response.Status.BAD_REQUEST);
        user = resolver.getUserFromIdTokenHint(userHint);
    } else if (authRequestedUserHint.equals(CibaGrantType.LOGIN_HINT_TOKEN)) {
        userHint = endpointRequest.getLoginHintToken();
        if (userHint == null)
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "missing parameter : login_hint_token", Response.Status.BAD_REQUEST);
        user = resolver.getUserFromLoginHintToken(userHint);
    } else {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "invalid user hint", Response.Status.BAD_REQUEST);
    }
    if (user == null || !user.isEnabled())
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "invalid user", Response.Status.BAD_REQUEST);
    return user;
}
Also used : UserModel(org.keycloak.models.UserModel) CIBALoginUserResolver(org.keycloak.protocol.oidc.grants.ciba.resolvers.CIBALoginUserResolver) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 58 with ErrorResponseException

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

the class DockerEndpoint method build.

@GET
public Response build() {
    ProfileHelper.requireFeature(Profile.Feature.DOCKER);
    final MultivaluedMap<String, String> params = session.getContext().getUri().getQueryParameters();
    account = params.getFirst(DockerAuthV2Protocol.ACCOUNT_PARAM);
    if (account == null) {
        logger.debug("Account parameter not provided by docker auth.  This is techincally required, but not actually used since " + "username is provided by Basic auth header.");
    }
    service = params.getFirst(DockerAuthV2Protocol.SERVICE_PARAM);
    if (service == null) {
        throw new ErrorResponseException("invalid_request", "service parameter must be provided", Response.Status.BAD_REQUEST);
    }
    client = realm.getClientByClientId(service);
    if (client == null) {
        logger.errorv("Failed to lookup client given by service={0} parameter for realm: {1}.", service, realm.getName());
        throw new ErrorResponseException("invalid_client", "Client specified by 'service' parameter does not exist", Response.Status.BAD_REQUEST);
    }
    scope = params.getFirst(DockerAuthV2Protocol.SCOPE_PARAM);
    checkSsl();
    checkRealm();
    final AuthorizationEndpointRequest authRequest = AuthorizationEndpointRequestParserProcessor.parseRequest(event, session, client, params);
    authenticationSession = createAuthenticationSession(client, authRequest.getState());
    updateAuthenticationSession();
    // So back button doesn't work
    CacheControlUtil.noBackButtonCacheControlHeader();
    return handleBrowserAuthenticationRequest(authenticationSession, new DockerAuthV2Protocol(session, realm, session.getContext().getUri(), headers, event.event(login)), false, false);
}
Also used : AuthorizationEndpointRequest(org.keycloak.protocol.oidc.endpoints.request.AuthorizationEndpointRequest) ErrorResponseException(org.keycloak.services.ErrorResponseException) GET(javax.ws.rs.GET)

Example 59 with ErrorResponseException

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

the class BitbucketIdentityProvider method validateExternalTokenThroughUserInfo.

@Override
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);
    }
    String type = getJsonProperty(profile, "type");
    if (type == null) {
        event.detail(Details.REASON, "no type data in user info response");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    if (type.equals("error")) {
        JsonNode errorNode = profile.get("error");
        if (errorNode != null) {
            String errorMsg = getJsonProperty(errorNode, "message");
            event.detail(Details.REASON, "user info call failure: " + errorMsg);
            event.error(Errors.INVALID_TOKEN);
            throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
        } else {
            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);
        }
    }
    if (!type.equals("user")) {
        event.detail(Details.REASON, "no user info in response");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    String id = getJsonProperty(profile, "account_id");
    if (id == 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 extractUserInfo(subjectToken, profile);
}
Also used : SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) ErrorResponseException(org.keycloak.services.ErrorResponseException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException)

Example 60 with ErrorResponseException

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

the class AbstractClientRegistrationProvider method update.

public ClientRepresentation update(String clientId, ClientRegistrationContext context) {
    ClientRepresentation rep = context.getClient();
    event.event(EventType.CLIENT_UPDATE).client(clientId);
    ClientModel client = session.getContext().getRealm().getClientByClientId(clientId);
    RegistrationAuth registrationAuth = auth.requireUpdate(context, client);
    if (!client.getClientId().equals(rep.getClientId())) {
        throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier modified", Response.Status.BAD_REQUEST);
    }
    RepresentationToModel.updateClient(rep, client);
    RepresentationToModel.updateClientProtocolMappers(rep, client);
    if (rep.getDefaultRoles() != null) {
        client.updateDefaultRoles(rep.getDefaultRoles());
    }
    rep = ModelToRepresentation.toRepresentation(client, session);
    Stream<String> defaultRolesNames = client.getDefaultRolesStream();
    if (defaultRolesNames != null) {
        rep.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
    }
    if (auth.isRegistrationAccessToken()) {
        String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, client, auth.getRegistrationAuth());
        rep.setRegistrationAccessToken(registrationAccessToken);
    }
    try {
        session.clientPolicy().triggerOnEvent(new DynamicClientUpdatedContext(session, client, auth.getJwt(), client.getRealm()));
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
    ClientRegistrationPolicyManager.triggerAfterUpdate(context, registrationAuth, client);
    event.client(client.getClientId()).success();
    return rep;
}
Also used : ClientModel(org.keycloak.models.ClientModel) RegistrationAuth(org.keycloak.services.clientregistration.policy.RegistrationAuth) DynamicClientUpdatedContext(org.keycloak.services.clientpolicy.context.DynamicClientUpdatedContext) ErrorResponseException(org.keycloak.services.ErrorResponseException) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException)

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