Search in sources :

Example 41 with ErrorResponseException

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

the class ClientAttributeCertificateResource method generateAndGetKeystore.

/**
 * Generate a new keypair and certificate, and get the private key file
 *
 * Generates a keypair and certificate and serves the private key in a specified keystore format.
 * Only generated public certificate is saved in Keycloak DB - the private key is not.
 *
 * @param config Keystore configuration as JSON
 * @return
 */
@POST
@NoCache
@Path("/generate-and-download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public byte[] generateAndGetKeystore(final KeyStoreConfig config) {
    auth.clients().requireConfigure(client);
    if (config.getFormat() != null && !config.getFormat().equals("JKS") && !config.getFormat().equals("PKCS12")) {
        throw new NotAcceptableException("Only support jks or pkcs12 format.");
    }
    if (config.getKeyPassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a key password for jks generation and download", Response.Status.BAD_REQUEST);
    }
    if (config.getStorePassword() == null) {
        throw new ErrorResponseException("password-missing", "Need to specify a store password for jks generation and download", Response.Status.BAD_REQUEST);
    }
    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());
    byte[] rtn = getKeystore(config, info.getPrivateKey(), info.getCertificate());
    info.setPrivateKey(null);
    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
    return rtn;
}
Also used : NotAcceptableException(javax.ws.rs.NotAcceptableException) CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) ErrorResponseException(org.keycloak.services.ErrorResponseException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 42 with ErrorResponseException

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

the class ClientAttributeCertificateResource method uploadJks.

/**
 * Upload certificate and eventually private key
 *
 * @param input
 * @return
 * @throws IOException
 */
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation uploadJks(MultipartFormDataInput input) throws IOException {
    auth.clients().requireConfigure(client);
    try {
        CertificateRepresentation info = getCertFromRequest(input);
        CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);
        adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
        return info;
    } catch (IllegalStateException ise) {
        throw new ErrorResponseException("certificate-not-found", "Certificate or key with given alias not found in the keystore", Response.Status.BAD_REQUEST);
    }
}
Also used : CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) 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)

Example 43 with ErrorResponseException

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

the class OIDCIdentityProvider method extractIdentityFromProfile.

@Override
protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode userInfo) {
    String id = getJsonProperty(userInfo, "sub");
    if (id == null) {
        event.detail(Details.REASON, "sub claim is null from user info json");
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "invalid token", Response.Status.BAD_REQUEST);
    }
    BrokeredIdentityContext identity = new BrokeredIdentityContext(id);
    String name = getJsonProperty(userInfo, "name");
    String preferredUsername = getUsernameFromUserInfo(userInfo);
    String givenName = getJsonProperty(userInfo, "given_name");
    String familyName = getJsonProperty(userInfo, "family_name");
    String email = getJsonProperty(userInfo, "email");
    AbstractJsonUserAttributeMapper.storeUserProfileForMapper(identity, userInfo, getConfig().getAlias());
    identity.setId(id);
    if (givenName != null) {
        identity.setFirstName(givenName);
    }
    if (familyName != null) {
        identity.setLastName(familyName);
    }
    if (givenName == null && familyName == null) {
        identity.setName(name);
    }
    identity.setEmail(email);
    identity.setBrokerUserId(getConfig().getAlias() + "." + id);
    if (preferredUsername == null) {
        preferredUsername = email;
    }
    if (preferredUsername == null) {
        preferredUsername = id;
    }
    identity.setUsername(preferredUsername);
    return identity;
}
Also used : ErrorResponseException(org.keycloak.services.ErrorResponseException) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Example 44 with ErrorResponseException

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

the class OpenShiftTokenReviewEndpoint method error.

private void error(int statusCode, String error, String description) {
    OpenShiftTokenReviewResponseRepresentation rep = new OpenShiftTokenReviewResponseRepresentation();
    rep.getStatus().setAuthenticated(false);
    Response response = Response.status(statusCode).entity(rep).type(MediaType.APPLICATION_JSON_TYPE).build();
    event.error(error);
    event.detail(Details.REASON, description);
    throw new ErrorResponseException(response);
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 45 with ErrorResponseException

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

the class BackchannelAuthenticationCallbackEndpoint method sendClientNotificationRequest.

protected void sendClientNotificationRequest(ClientModel client, CibaConfig cibaConfig, OAuth2DeviceCodeModel deviceModel) {
    String clientNotificationEndpoint = cibaConfig.getBackchannelClientNotificationEndpoint(client);
    if (clientNotificationEndpoint == null) {
        event.error(Errors.INVALID_REQUEST);
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client notification endpoint not set for the client with the ping mode", Response.Status.BAD_REQUEST);
    }
    logger.debugf("Sending request to client notification endpoint '%s' for the client '%s'", clientNotificationEndpoint, client.getClientId());
    ClientNotificationEndpointRequest clientNotificationRequest = new ClientNotificationEndpointRequest();
    clientNotificationRequest.setAuthReqId(deviceModel.getAuthReqId());
    SimpleHttp simpleHttp = SimpleHttp.doPost(clientNotificationEndpoint, session).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).json(clientNotificationRequest).auth(deviceModel.getClientNotificationToken());
    try {
        int notificationResponseStatus = simpleHttp.asStatus();
        logger.tracef("Received status '%d' from request to client notification endpoint '%s' for the client '%s'", notificationResponseStatus, clientNotificationEndpoint, client.getClientId());
        if (notificationResponseStatus != 200 && notificationResponseStatus != 204) {
            logger.warnf("Invalid status returned from client notification endpoint '%s' of client '%s'", clientNotificationEndpoint, client.getClientId());
            event.error(Errors.INVALID_REQUEST);
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to send request to client notification endpoint", Response.Status.BAD_REQUEST);
        }
    } catch (IOException ioe) {
        logger.errorf(ioe, "Failed to send request to client notification endpoint '%s' of client '%s'", clientNotificationEndpoint, client.getClientId());
        event.error(Errors.INVALID_REQUEST);
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to send request to client notification endpoint", Response.Status.BAD_REQUEST);
    }
}
Also used : SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException)

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