Search in sources :

Example 11 with CertificateRepresentation

use of org.keycloak.representations.idm.CertificateRepresentation in project keycloak by keycloak.

the class ClientAttributeCertificateResource method generate.

/**
 * Generate a new certificate with new key pair
 *
 * @return
 */
@POST
@NoCache
@Path("generate")
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation generate() {
    auth.clients().requireConfigure(client);
    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());
    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
    return info;
}
Also used : CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 12 with CertificateRepresentation

use of org.keycloak.representations.idm.CertificateRepresentation in project keycloak by keycloak.

the class ClientAttributeCertificateResource method uploadJksCertificate.

/**
 * Upload only certificate, not private key
 *
 * @param input
 * @return information extracted from uploaded certificate - not necessarily the new state of certificate on the server
 * @throws IOException
 */
@POST
@Path("upload-certificate")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation uploadJksCertificate(MultipartFormDataInput input) throws IOException {
    auth.clients().requireConfigure(client);
    try {
        CertificateRepresentation info = getCertFromRequest(input);
        info.setPrivateKey(null);
        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 13 with CertificateRepresentation

use of org.keycloak.representations.idm.CertificateRepresentation in project keycloak by keycloak.

the class OIDCAdvancedRequestParamsTest method requestUriParamSigned.

@Test
public void requestUriParamSigned() throws Exception {
    String validRedirectUri = oauth.getRedirectUri();
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    // Set required signature for request_uri
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
    ClientRepresentation clientRep = clientResource.toRepresentation();
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectSignatureAlg(Algorithm.RS256);
    clientResource.update(clientRep);
    // Verify unsigned request_uri will fail
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", validRedirectUri, "10", Algorithm.none.toString());
    oauth.requestUri(TestApplicationResourceUrls.clientRequestUri());
    oauth.openLoginForm();
    Assert.assertTrue(errorPage.isCurrent());
    assertEquals("Invalid Request", errorPage.getError());
    // Generate keypair for client
    String clientPublicKeyPem = oidcClientEndpointsResource.generateKeys("RS256").get(TestingOIDCEndpointsApplicationResource.PUBLIC_KEY);
    // Verify signed request_uri will fail due to failed signature validation
    oidcClientEndpointsResource.setOIDCRequest("test", "test-app", validRedirectUri, "10", "mystate3", Algorithm.RS256.toString());
    oauth.openLoginForm();
    Assert.assertTrue(errorPage.isCurrent());
    assertEquals("Invalid Request", errorPage.getError());
    // Update clientModel with publicKey for signing
    clientRep = clientResource.toRepresentation();
    CertificateRepresentation cert = new CertificateRepresentation();
    cert.setPublicKey(clientPublicKeyPem);
    CertificateInfoHelper.updateClientRepresentationCertificateInfo(clientRep, cert, JWTClientAuthenticator.ATTR_PREFIX);
    clientResource.update(clientRep);
    // set time offset, so that new keys are downloaded
    setTimeOffset(20);
    // Check signed request_uri will pass
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
    Assert.assertNotNull(response.getCode());
    Assert.assertEquals("mystate3", response.getState());
    assertTrue(appPage.isCurrent());
    // Revert requiring signature for client
    OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setRequestObjectSignatureAlg(null);
    clientResource.update(clientRep);
}
Also used : TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OAuthClient(org.keycloak.testsuite.util.OAuthClient) CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 14 with CertificateRepresentation

use of org.keycloak.representations.idm.CertificateRepresentation in project keycloak by keycloak.

the class CredentialsTest method testDownloadKeystore.

@Test
public void testDownloadKeystore() throws Exception {
    ClientAttributeCertificateResource certRsc = accountClient.getCertficateResource("jwt.credential");
    // generate a key pair first
    CertificateRepresentation certrep = certRsc.generate();
    // download the key and certificate
    KeyStoreConfig config = new KeyStoreConfig();
    config.setFormat("JKS");
    config.setKeyAlias("alias");
    config.setKeyPassword("keyPass");
    config.setStorePassword("storePass");
    byte[] result = certRsc.getKeystore(config);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new ByteArrayInputStream(result), "storePass".toCharArray());
    Key key = keyStore.getKey("alias", "keyPass".toCharArray());
    Certificate cert = keyStore.getCertificate("alias");
    assertTrue("Certificat is X509", cert instanceof X509Certificate);
    String keyPem = KeycloakModelUtils.getPemFromKey(key);
    String certPem = KeycloakModelUtils.getPemFromCertificate((X509Certificate) cert);
    assertEquals("key match", certrep.getPrivateKey(), keyPem);
    assertEquals("cert match", certrep.getCertificate(), certPem);
}
Also used : ClientAttributeCertificateResource(org.keycloak.admin.client.resource.ClientAttributeCertificateResource) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateRepresentation(org.keycloak.representations.idm.CertificateRepresentation) KeyStore(java.security.KeyStore) Key(java.security.Key) X509Certificate(java.security.cert.X509Certificate) KeyStoreConfig(org.keycloak.representations.KeyStoreConfig) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 15 with CertificateRepresentation

use of org.keycloak.representations.idm.CertificateRepresentation 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)

Aggregations

CertificateRepresentation (org.keycloak.representations.idm.CertificateRepresentation)17 Produces (javax.ws.rs.Produces)6 POST (javax.ws.rs.POST)5 Path (javax.ws.rs.Path)5 Test (org.junit.Test)5 ErrorResponseException (org.keycloak.services.ErrorResponseException)5 X509Certificate (java.security.cert.X509Certificate)4 Consumes (javax.ws.rs.Consumes)4 NoCache (org.jboss.resteasy.annotations.cache.NoCache)4 ClientAttributeCertificateResource (org.keycloak.admin.client.resource.ClientAttributeCertificateResource)4 KeyStore (java.security.KeyStore)3 NotAcceptableException (javax.ws.rs.NotAcceptableException)3 JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 Key (java.security.Key)2 PublicKey (java.security.PublicKey)2 Certificate (java.security.cert.Certificate)2 NotFoundException (javax.ws.rs.NotFoundException)2 JWK (org.keycloak.jose.jwk.JWK)2