Search in sources :

Example 11 with JWSBuilder

use of org.keycloak.jose.jws.JWSBuilder in project keycloak by keycloak.

the class KeyPairVerifier method verify.

public static void verify(String privateKeyPem, String publicKeyPem) throws VerificationException {
    PrivateKey privateKey;
    try {
        privateKey = PemUtils.decodePrivateKey(privateKeyPem);
    } catch (Exception e) {
        throw new VerificationException("Failed to decode private key");
    }
    PublicKey publicKey;
    try {
        publicKey = PemUtils.decodePublicKey(publicKeyPem);
    } catch (Exception e) {
        throw new VerificationException("Failed to decode public key");
    }
    try {
        String jws = new JWSBuilder().content("content".getBytes()).rsa256(privateKey);
        if (!RSAProvider.verify(new JWSInput(jws), publicKey)) {
            throw new VerificationException("Keys don't match");
        }
    } catch (Exception e) {
        throw new VerificationException("Keys don't match");
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) VerificationException(org.keycloak.common.VerificationException) JWSInput(org.keycloak.jose.jws.JWSInput) VerificationException(org.keycloak.common.VerificationException) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 12 with JWSBuilder

use of org.keycloak.jose.jws.JWSBuilder 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 13 with JWSBuilder

use of org.keycloak.jose.jws.JWSBuilder in project keycloak by keycloak.

the class AbstractClientPoliciesTest method createSignedRequestToken.

// Signed JWT for client authentication utility
protected String createSignedRequestToken(String clientId, PrivateKey privateKey, PublicKey publicKey, String algorithm) {
    JsonWebToken jwt = createRequestToken(clientId, getRealmInfoUrl());
    String kid = KeyUtils.createKeyId(publicKey);
    SignatureSignerContext signer = oauth.createSigner(privateKey, kid, algorithm);
    return new JWSBuilder().kid(kid).jsonContent(jwt).sign(signer);
}
Also used : SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) JsonWebToken(org.keycloak.representations.JsonWebToken) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 14 with JWSBuilder

use of org.keycloak.jose.jws.JWSBuilder in project keycloak by keycloak.

the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak25.

// KEYCLOAK-5440 -- migration from Keycloak 3.1.0
@Test
public void testRestartCookieBackwardsCompatible_Keycloak25() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");
            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
            String encodedToken = new JWSBuilder().kid(activeKey.getKid()).content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
            return encodedToken;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    oauth.openLoginForm();
    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
Also used : RealmModel(org.keycloak.models.RealmModel) RestartLoginCookie(org.keycloak.protocol.RestartLoginCookie) Cookie(org.openqa.selenium.Cookie) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) KeyManager(org.keycloak.models.KeyManager) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 15 with JWSBuilder

use of org.keycloak.jose.jws.JWSBuilder in project keycloak by keycloak.

the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak19.

// KEYCLOAK-7158 -- migration from Keycloak 1.9.8
@Test
public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");
            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
            // There was no KID in the token in Keycloak 1.9.8
            String encodedToken = new JWSBuilder().content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
            return encodedToken;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });
    oauth.openLoginForm();
    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
Also used : RealmModel(org.keycloak.models.RealmModel) RestartLoginCookie(org.keycloak.protocol.RestartLoginCookie) Cookie(org.openqa.selenium.Cookie) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) KeyManager(org.keycloak.models.KeyManager) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

JWSBuilder (org.keycloak.jose.jws.JWSBuilder)28 Test (org.junit.Test)15 AccessToken (org.keycloak.representations.AccessToken)12 VerificationException (org.keycloak.common.VerificationException)8 SignatureSignerContext (org.keycloak.crypto.SignatureSignerContext)6 KeyPair (java.security.KeyPair)5 RealmModel (org.keycloak.models.RealmModel)4 JsonWebToken (org.keycloak.representations.JsonWebToken)4 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)4 SecretKey (javax.crypto.SecretKey)3 Response (javax.ws.rs.core.Response)3 JWSInput (org.keycloak.jose.jws.JWSInput)3 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)3 KeyManager (org.keycloak.models.KeyManager)3 KeycloakSession (org.keycloak.models.KeycloakSession)3 UserSessionModel (org.keycloak.models.UserSessionModel)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 ObjectInputStream (java.io.ObjectInputStream)2