Search in sources :

Example 6 with ErrorResponseException

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

the class BackchannelAuthenticationCallbackEndpoint method verifyAuthenticationRequest.

private BackchannelAuthCallbackContext verifyAuthenticationRequest(HttpHeaders headers) {
    String rawBearerToken = AppAuthManager.extractAuthorizationHeaderTokenOrReturnNull(headers);
    if (rawBearerToken == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.UNAUTHORIZED);
    }
    AccessToken bearerToken;
    try {
        bearerToken = TokenVerifier.createWithoutSignature(session.tokens().decode(rawBearerToken, AccessToken.class)).withDefaultChecks().realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).checkActive(true).audience(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).verify().getToken();
    } catch (Exception e) {
        event.error(Errors.INVALID_TOKEN);
        // authentication channel id format is invalid or it has already been used
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
    OAuth2DeviceCodeModel deviceCode = store.getByUserCode(realm, bearerToken.getId());
    if (deviceCode == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    if (!deviceCode.isPending()) {
        cancelRequest(bearerToken.getId());
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    ClientModel issuedFor = realm.getClientByClientId(bearerToken.getIssuedFor());
    if (issuedFor == null || !issuedFor.isEnabled()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid token recipient", Response.Status.BAD_REQUEST);
    }
    if (!deviceCode.getClientId().equals(issuedFor.getClientId())) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Token recipient mismatch", Response.Status.BAD_REQUEST);
    }
    session.getContext().setClient(issuedFor);
    event.client(issuedFor);
    return new BackchannelAuthCallbackContext(bearerToken, deviceCode);
}
Also used : OAuth2DeviceTokenStoreProvider(org.keycloak.models.OAuth2DeviceTokenStoreProvider) ClientModel(org.keycloak.models.ClientModel) OAuth2DeviceCodeModel(org.keycloak.models.OAuth2DeviceCodeModel) AccessToken(org.keycloak.representations.AccessToken) ErrorResponseException(org.keycloak.services.ErrorResponseException) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException)

Example 7 with ErrorResponseException

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

the class BackchannelAuthenticationCallbackEndpoint method processAuthenticationChannelResult.

@Path("/")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response processAuthenticationChannelResult(AuthenticationChannelResponse response) {
    event.event(EventType.LOGIN);
    BackchannelAuthCallbackContext ctx = verifyAuthenticationRequest(httpRequest.getHttpHeaders());
    AccessToken bearerToken = ctx.bearerToken;
    OAuth2DeviceCodeModel deviceModel = ctx.deviceModel;
    Status status = response.getStatus();
    if (status == null) {
        event.error(Errors.INVALID_REQUEST);
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authentication status", Response.Status.BAD_REQUEST);
    }
    switch(status) {
        case SUCCEED:
            approveRequest(bearerToken, response.getAdditionalParams());
            break;
        case CANCELLED:
        case UNAUTHORIZED:
            denyRequest(bearerToken, status);
            break;
    }
    // Call the notification endpoint
    ClientModel client = session.getContext().getClient();
    CibaConfig cibaConfig = realm.getCibaPolicy();
    if (cibaConfig.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
        sendClientNotificationRequest(client, cibaConfig, deviceModel);
    }
    return Response.ok(MediaType.APPLICATION_JSON_TYPE).build();
}
Also used : Status(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelResponse.Status) ClientModel(org.keycloak.models.ClientModel) OAuth2DeviceCodeModel(org.keycloak.models.OAuth2DeviceCodeModel) AccessToken(org.keycloak.representations.AccessToken) CibaConfig(org.keycloak.models.CibaConfig) ErrorResponseException(org.keycloak.services.ErrorResponseException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 8 with ErrorResponseException

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

the class UserResource method resetPassword.

/**
 * Set up a new password for the user.
 *
 * @param cred The representation must contain a rawPassword with the plain-text password
 */
@Path("reset-password")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void resetPassword(CredentialRepresentation cred) {
    auth.users().requireManage(user);
    if (cred == null || cred.getValue() == null) {
        throw new BadRequestException("No password provided");
    }
    if (Validation.isBlank(cred.getValue())) {
        throw new BadRequestException("Empty password not allowed");
    }
    try {
        session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false));
    } catch (IllegalStateException ise) {
        throw new BadRequestException("Resetting to N old passwords is not allowed.");
    } catch (ReadOnlyException mre) {
        throw new BadRequestException("Can't reset password as account is read only");
    } catch (ModelException e) {
        logger.warn("Could not update user password.", e);
        Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
        throw new ErrorResponseException(e.getMessage(), MessageFormat.format(messages.getProperty(e.getMessage(), e.getMessage()), e.getParameters()), Status.BAD_REQUEST);
    }
    if (cred.isTemporary() != null && cred.isTemporary()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    } else {
        // Remove a potentially existing UPDATE_PASSWORD action when explicitly assigning a non-temporary password.
        user.removeRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
Also used : ModelException(org.keycloak.models.ModelException) BadRequestException(javax.ws.rs.BadRequestException) ErrorResponseException(org.keycloak.services.ErrorResponseException) Properties(java.util.Properties) ReadOnlyException(org.keycloak.storage.ReadOnlyException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 9 with ErrorResponseException

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

the class RoleByIdResource method deleteRole.

/**
 * Delete the role
 *
 * @param id id of role
 */
@Path("{role-id}")
@DELETE
@NoCache
public void deleteRole(@PathParam("role-id") final String id) {
    if (realm.getDefaultRole() == null) {
        logger.warnf("Default role for realm with id '%s' doesn't exist.", realm.getId());
    } else if (realm.getDefaultRole().getId().equals(id)) {
        throw new ErrorResponseException(ErrorResponse.error(realm.getDefaultRole().getName() + " is default role of the realm and cannot be removed.", Response.Status.BAD_REQUEST));
    }
    RoleModel role = getRoleModel(id);
    auth.roles().requireManage(role);
    deleteRole(role);
    if (role.isClientRole()) {
        adminEvent.resource(ResourceType.CLIENT_ROLE);
    } else {
        adminEvent.resource(ResourceType.REALM_ROLE);
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
}
Also used : ErrorResponseException(org.keycloak.services.ErrorResponseException) RoleModel(org.keycloak.models.RoleModel) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 10 with ErrorResponseException

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

the class AuthenticationManager method frontchannelLogoutClientSession.

private static Response frontchannelLogoutClientSession(KeycloakSession session, RealmModel realm, AuthenticatedClientSessionModel clientSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo, HttpHeaders headers) {
    UserSessionModel userSession = clientSession.getUserSession();
    ClientModel client = clientSession.getClient();
    if (!client.isFrontchannelLogout() || AuthenticationSessionModel.Action.LOGGED_OUT.name().equals(clientSession.getAction())) {
        return null;
    }
    final AuthenticationSessionModel.Action logoutState = getClientLogoutAction(logoutAuthSession, client.getId());
    if (logoutState == AuthenticationSessionModel.Action.LOGGED_OUT || logoutState == AuthenticationSessionModel.Action.LOGGING_OUT) {
        return null;
    }
    try {
        session.clientPolicy().triggerOnEvent(new LogoutRequestContext());
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), cpe.getErrorStatus());
    }
    try {
        setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGING_OUT);
        String authMethod = clientSession.getProtocol();
        // must be a keycloak service like account
        if (authMethod == null)
            return null;
        logger.debugv("frontchannel logout to: {0}", client.getClientId());
        LoginProtocol protocol = session.getProvider(LoginProtocol.class, authMethod);
        protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo);
        Response response = protocol.frontchannelLogout(userSession, clientSession);
        if (response != null) {
            logger.debug("returning frontchannel logout request to client");
            if (!AuthenticationSessionModel.Action.LOGGING_OUT.name().equals(clientSession.getAction())) {
                setClientLogoutAction(logoutAuthSession, client.getId(), AuthenticationSessionModel.Action.LOGGED_OUT);
            }
            return response;
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToLogoutClient(e);
    }
    return null;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) LoginProtocol(org.keycloak.protocol.LoginProtocol) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) VerificationException(org.keycloak.common.VerificationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) 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