Search in sources :

Example 21 with JWSBuilder

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

the class SkeletonKeyTokenTest method testRSA.

@Test
public void testRSA() throws Exception {
    AccessToken token = createSimpleToken();
    token.id("111");
    token.addAccess("foo").addRole("admin");
    token.addAccess("bar").addRole("user");
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    String encoded = new JWSBuilder().jsonContent(token).rsa256(keyPair.getPrivate());
    JWSInput input = new JWSInput(encoded);
    token = input.readJsonContent(AccessToken.class);
    Assert.assertEquals("111", token.getId());
    Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
Also used : KeyPair(java.security.KeyPair) AccessToken(org.keycloak.representations.AccessToken) JWSInput(org.keycloak.jose.jws.JWSInput) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 22 with JWSBuilder

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

the class AuthUtil method getSignedRequestToken.

public static String getSignedRequestToken(String keystore, String storePass, String keyPass, String alias, int sigLifetime, String clientId, String realmInfoUrl) {
    KeyPair keypair = KeystoreUtil.loadKeyPairFromKeystore(keystore, storePass, keyPass, alias, KeystoreUtil.KeystoreFormat.JKS);
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(UUID.randomUUID().toString());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);
    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + sigLifetime);
    reqToken.notBefore(now);
    String signedRequestToken = new JWSBuilder().jsonContent(reqToken).rsa256(keypair.getPrivate());
    return signedRequestToken;
}
Also used : KeyPair(java.security.KeyPair) JsonWebToken(org.keycloak.representations.JsonWebToken) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 23 with JWSBuilder

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

the class OIDCAdvancedRequestParamsTest method processClaimsRequestParam.

@Test
public void processClaimsRequestParam() throws Exception {
    Map<String, Object> claims = ImmutableMap.of("id_token", ImmutableMap.of("test_claim", ImmutableMap.of("essential", true)));
    String claimsJson = JsonSerialization.writeValueAsString(claims);
    Map<String, Object> oidcRequest = new HashMap<>();
    oidcRequest.put(OIDCLoginProtocol.CLIENT_ID_PARAM, "test-app");
    oidcRequest.put(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
    oidcRequest.put(OIDCLoginProtocol.REDIRECT_URI_PARAM, oauth.getRedirectUri());
    oidcRequest.put(OIDCLoginProtocol.CLAIMS_PARAM, claims);
    String request = new JWSBuilder().jsonContent(oidcRequest).none();
    driver.navigate().to(oauth.getLoginFormUrl() + "&" + OIDCLoginProtocol.REQUEST_PARAM + "=" + request);
    // need to login so session id can be read from event
    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String clientId = loginEvent.getClientId();
    testingClient.server("test").run(session -> {
        RealmModel realmModel = session.getContext().getRealm();
        String clientUuid = realmModel.getClientByClientId(clientId).getId();
        UserSessionModel userSession = session.sessions().getUserSession(realmModel, sessionId);
        AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUuid);
        String claimsInSession = clientSession.getNote(OIDCLoginProtocol.CLAIMS_PARAM);
        assertEquals(claimsJson, claimsInSession);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 24 with JWSBuilder

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

the class CIBAAuthenticationRequest method serialize.

/**
 * Serializes this instance to a JWE.
 *
 * @param session the session
 * @return the JWE
 */
public String serialize(KeycloakSession session) {
    try {
        SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, Algorithm.HS256);
        SignatureSignerContext signer = signatureProvider.signer();
        String encodedJwt = new JWSBuilder().type("JWT").jsonContent(this).sign(signer);
        SecretKey aesKey = session.keys().getActiveKey(session.getContext().getRealm(), KeyUse.ENC, Algorithm.AES).getSecretKey();
        SecretKey hmacKey = session.keys().getActiveKey(session.getContext().getRealm(), KeyUse.SIG, Algorithm.HS256).getSecretKey();
        return TokenUtil.jweDirectEncode(aesKey, hmacKey, encodedJwt.getBytes("UTF-8"));
    } catch (JWEException | UnsupportedEncodingException e) {
        throw new RuntimeException("Error encoding auth_req_id.", e);
    }
}
Also used : SignatureProvider(org.keycloak.crypto.SignatureProvider) SecretKey(javax.crypto.SecretKey) SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

Example 25 with JWSBuilder

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

the class OIDCJwksClientRegistrationTest method getClientSignedJWT.

private String getClientSignedJWT(String clientId, KeyPair keyPair, final String kid) {
    String realmInfoUrl = KeycloakUriBuilder.fromUri(getAuthServerRoot()).path(ServiceUrlConstants.REALM_INFO_PATH).build(REALM_NAME).toString();
    // Use token-endpoint as audience as OIDC conformance testsuite is using it too.
    JWTClientCredentialsProvider jwtProvider = new JWTClientCredentialsProvider() {

        @Override
        public String createSignedRequestToken(String clientId, String realmInfoUrl) {
            if (KEEP_GENERATED_KID.equals(kid)) {
                return super.createSignedRequestToken(clientId, realmInfoUrl);
            } else {
                JsonWebToken jwt = createRequestToken(clientId, realmInfoUrl);
                return new JWSBuilder().kid(kid).jsonContent(jwt).rsa256(keyPair.getPrivate());
            }
        }

        @Override
        protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
            JsonWebToken jwt = super.createRequestToken(clientId, realmInfoUrl);
            String tokenEndpointUrl = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(getAuthServerRoot())).build(REALM_NAME).toString();
            jwt.audience(tokenEndpointUrl);
            return jwt;
        }
    };
    jwtProvider.setupKeyPair(keyPair);
    jwtProvider.setTokenTimeout(10);
    return jwtProvider.createSignedRequestToken(clientId, realmInfoUrl);
}
Also used : JsonWebToken(org.keycloak.representations.JsonWebToken) JWTClientCredentialsProvider(org.keycloak.adapters.authentication.JWTClientCredentialsProvider) JWSBuilder(org.keycloak.jose.jws.JWSBuilder)

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