Search in sources :

Example 1 with ErrorResponseException

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

the class DockerAuthV2Protocol method authenticated.

@Override
public Response authenticated(final AuthenticationSessionModel authSession, final UserSessionModel userSession, final ClientSessionContext clientSessionCtx) {
    // First, create a base response token with realm + user values populated
    final AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    final ClientModel client = clientSession.getClient();
    DockerResponseToken responseToken = new DockerResponseToken().id(KeycloakModelUtils.generateId()).type(TokenUtil.TOKEN_TYPE_BEARER).issuer(authSession.getClientNote(DockerAuthV2Protocol.ISSUER)).subject(userSession.getUser().getUsername()).issuedNow().audience(client.getClientId()).issuedFor(client.getClientId());
    // since realm access token is given in seconds
    final int accessTokenLifespan = realm.getAccessTokenLifespan();
    responseToken.notBefore(responseToken.getIssuedAt()).expiration(responseToken.getIssuedAt() + accessTokenLifespan);
    // Next, allow mappers to decorate the token to add/remove scopes as appropriate
    AtomicReference<DockerResponseToken> finalResponseToken = new AtomicReference<>(responseToken);
    ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx).filter(mapper -> mapper.getValue() instanceof DockerAuthV2AttributeMapper).filter(mapper -> ((DockerAuthV2AttributeMapper) mapper.getValue()).appliesTo(finalResponseToken.get())).forEach(mapper -> finalResponseToken.set(((DockerAuthV2AttributeMapper) mapper.getValue()).transformDockerResponseToken(finalResponseToken.get(), mapper.getKey(), session, userSession, clientSession)));
    responseToken = finalResponseToken.get();
    try {
        // Finally, construct the response to the docker client with the token + metadata
        if (event.getEvent() != null && EventType.LOGIN.equals(event.getEvent().getType())) {
            final KeyManager.ActiveRsaKey activeKey = session.keys().getActiveRsaKey(realm);
            final String encodedToken = new JWSBuilder().kid(new DockerKeyIdentifier(activeKey.getPublicKey()).toString()).type("JWT").jsonContent(responseToken).rsa256(activeKey.getPrivateKey());
            final String expiresInIso8601String = new SimpleDateFormat(ISO_8601_DATE_FORMAT).format(new Date(responseToken.getIssuedAt() * 1000L));
            final DockerResponse responseEntity = new DockerResponse().setToken(encodedToken).setExpires_in(accessTokenLifespan).setIssued_at(expiresInIso8601String);
            return new ResponseBuilderImpl().status(Response.Status.OK).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(responseEntity).build();
        } else {
            logger.errorv("Unable to handle request for event type {0}.  Currently only LOGIN event types are supported by docker protocol.", event.getEvent() == null ? "null" : event.getEvent().getType());
            throw new ErrorResponseException("invalid_request", "Event type not supported", Response.Status.BAD_REQUEST);
        }
    } catch (final InstantiationException e) {
        logger.errorv("Error attempting to create Key ID for Docker JOSE header: ", e.getMessage());
        throw new ErrorResponseException("token_error", "Unable to construct JOSE header for JWT", Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : DockerAuthV2AttributeMapper(org.keycloak.protocol.docker.mapper.DockerAuthV2AttributeMapper) ClientModel(org.keycloak.models.ClientModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Date(java.util.Date) Logger(org.jboss.logging.Logger) SimpleDateFormat(java.text.SimpleDateFormat) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) AtomicReference(java.util.concurrent.atomic.AtomicReference) KeyManager(org.keycloak.models.KeyManager) TokenUtil(org.keycloak.util.TokenUtil) MediaType(javax.ws.rs.core.MediaType) ClientSessionContext(org.keycloak.models.ClientSessionContext) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) EventBuilder(org.keycloak.events.EventBuilder) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) DockerResponseToken(org.keycloak.representations.docker.DockerResponseToken) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) UserSessionModel(org.keycloak.models.UserSessionModel) DockerResponse(org.keycloak.representations.docker.DockerResponse) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) ProtocolMapperUtils(org.keycloak.protocol.ProtocolMapperUtils) UriInfo(javax.ws.rs.core.UriInfo) DockerAuthV2AttributeMapper(org.keycloak.protocol.docker.mapper.DockerAuthV2AttributeMapper) LoginProtocol(org.keycloak.protocol.LoginProtocol) DockerResponse(org.keycloak.representations.docker.DockerResponse) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) DockerResponseToken(org.keycloak.representations.docker.DockerResponseToken) Date(java.util.Date) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) ClientModel(org.keycloak.models.ClientModel) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) ErrorResponseException(org.keycloak.services.ErrorResponseException) KeyManager(org.keycloak.models.KeyManager) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with ErrorResponseException

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

the class ClientResource method update.

/**
 * Update the client
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response update(final ClientRepresentation rep) {
    auth.clients().requireConfigure(client);
    try {
        session.clientPolicy().triggerOnEvent(new AdminClientUpdateContext(rep, client, auth.adminAuth()));
        updateClientFromRep(rep, client, session);
        ValidationUtil.validateClient(session, client, false, r -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
        });
        session.clientPolicy().triggerOnEvent(new AdminClientUpdatedContext(rep, client, auth.adminAuth()));
        adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client already exists");
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : AdminClientUpdateContext(org.keycloak.services.clientpolicy.context.AdminClientUpdateContext) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException) AdminClientUpdatedContext(org.keycloak.services.clientpolicy.context.AdminClientUpdatedContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 3 with ErrorResponseException

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

the class RoleContainerResource method deleteRole.

/**
 * Delete a role by name
 *
 * @param roleName role's name (not id!)
 */
@Path("{role-name}")
@DELETE
@NoCache
public void deleteRole(@PathParam("role-name") final String roleName) {
    auth.roles().requireManage(roleContainer);
    RoleModel role = roleContainer.getRole(roleName);
    if (role == null) {
        throw new NotFoundException("Could not find role");
    } else if (realm.getDefaultRole().getId().equals(role.getId())) {
        throw new ErrorResponseException(ErrorResponse.error(roleName + " is default role of the realm and cannot be removed.", Response.Status.BAD_REQUEST));
    }
    deleteRole(role);
    if (role.isClientRole()) {
        adminEvent.resource(ResourceType.CLIENT_ROLE);
    } else {
        adminEvent.resource(ResourceType.REALM_ROLE);
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 4 with ErrorResponseException

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

the class ClientRoleMappingsResource method addClientRoleMapping.

/**
 * Add client-level roles to the user role mapping
 *
 * @param roles
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addClientRoleMapping(List<RoleRepresentation> roles) {
    managePermission.require();
    try {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = client.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            user.grantRole(roleModel);
        }
    } catch (ModelException | ReadOnlyException me) {
        logger.warn(me.getMessage(), me);
        throw new ErrorResponseException("invalid_request", "Could not add user role mappings!", Response.Status.BAD_REQUEST);
    }
    adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(roles).success();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ReadOnlyException(org.keycloak.storage.ReadOnlyException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 5 with ErrorResponseException

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

the class ClientRoleMappingsResource method deleteClientRoleMapping.

/**
 * Delete client-level roles from user role mapping
 *
 * @param roles
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteClientRoleMapping(List<RoleRepresentation> roles) {
    managePermission.require();
    if (roles == null) {
        roles = user.getClientRoleMappingsStream(client).peek(roleModel -> {
            auth.roles().requireMapRole(roleModel);
            user.deleteRoleMapping(roleModel);
        }).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
    } else {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = client.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            try {
                user.deleteRoleMapping(roleModel);
            } catch (ModelException | ReadOnlyException me) {
                logger.warn(me.getMessage(), me);
                throw new ErrorResponseException("invalid_request", "Could not remove user role mappings!", Response.Status.BAD_REQUEST);
            }
        }
    }
    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).representation(roles).success();
}
Also used : ClientModel(org.keycloak.models.ClientModel) OperationType(org.keycloak.events.admin.OperationType) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Path(javax.ws.rs.Path) Function(java.util.function.Function) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) ErrorResponseException(org.keycloak.services.ErrorResponseException) DefaultValue(javax.ws.rs.DefaultValue) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) POST(javax.ws.rs.POST) Predicate(java.util.function.Predicate) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) Stream(java.util.stream.Stream) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) ModelException(org.keycloak.models.ModelException) RoleMapperModel(org.keycloak.models.RoleMapperModel) UriInfo(javax.ws.rs.core.UriInfo) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ModelException(org.keycloak.models.ModelException) NotFoundException(javax.ws.rs.NotFoundException) RoleModel(org.keycloak.models.RoleModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) ReadOnlyException(org.keycloak.storage.ReadOnlyException) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

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