Search in sources :

Example 6 with JWSBuilder

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

the class RSAVerifierTest method testSimpleVerification.

@Test
public void testSimpleVerification() throws Exception {
    String encoded = new JWSBuilder().jsonContent(token).rsa256(idpPair.getPrivate());
    System.out.print("encoded size: " + encoded.length());
    AccessToken token = verifySkeletonKeyToken(encoded);
    Assert.assertTrue(token.getResourceAccess("service").getRoles().contains("admin"));
    Assert.assertEquals("CN=Client", token.getSubject());
}
Also used : AccessToken(org.keycloak.representations.AccessToken) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 7 with JWSBuilder

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

the class RSAVerifierTest method testBadSignature.

@Test
public void testBadSignature() {
    String encoded = new JWSBuilder().jsonContent(token).rsa256(badPair.getPrivate());
    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
        Assert.fail();
    } catch (VerificationException ignored) {
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 8 with JWSBuilder

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

the class HmacTest method testHmacSignatures.

@Test
public void testHmacSignatures() throws Exception {
    SecretKey secret = new SecretKeySpec(UUID.randomUUID().toString().getBytes(), "HmacSHA256");
    String encoded = new JWSBuilder().content("12345678901234567890".getBytes()).hmac256(secret);
    System.out.println("length: " + encoded.length());
    JWSInput input = new JWSInput(encoded);
    Assert.assertTrue(HMACProvider.verify(input, secret));
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JWSInput(org.keycloak.jose.jws.JWSInput) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 9 with JWSBuilder

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

the class OIDCAdvancedRequestParamsTest method processClaimsRequestParamSupported.

@Test
public void processClaimsRequestParamSupported() throws Exception {
    String clientScopeId = null;
    try {
        for (ClientScopeRepresentation rep : adminClient.realm("test").clientScopes().findAll()) {
            if (rep.getName().equals("profile")) {
                clientScopeId = rep.getId();
                break;
            }
        }
        findClientResourceByClientId(adminClient.realm("test"), "test-app").removeDefaultClientScope(clientScopeId);
        ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app");
        ProtocolMappersResource res = app.getProtocolMappers();
        res.createMapper(ModelToRepresentation.toRepresentation(ClaimsParameterTokenMapper.createMapper("claimsParameterTokenMapper", true, false))).close();
        Map<String, Object> claims = ImmutableMap.of("id_token", ImmutableMap.of("email", ImmutableMap.of("essential", true), "preferred_username", ImmutableMap.of("essential", true), "family_name", ImmutableMap.of("essential", false), "given_name", ImmutableMap.of("wesentlich", true), "name", ImmutableMap.of("essential", true)), "userinfo", ImmutableMap.of("preferred_username", ImmutableMap.of("essential", "Ja"), "family_name", ImmutableMap.of("essential", true), "given_name", ImmutableMap.of("essential", true)));
        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);
        oidcRequest.put(OIDCLoginProtocol.SCOPE_PARAM, "openid");
        String request = new JWSBuilder().jsonContent(oidcRequest).none();
        oauth = oauth.request(request);
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        OAuthClient.AccessTokenResponse accessTokenResponse = sendTokenRequestAndGetResponse(loginEvent);
        IDToken idToken = oauth.verifyIDToken(accessTokenResponse.getIdToken());
        assertEquals("test-user@localhost", idToken.getEmail());
        assertEquals("test-user@localhost", idToken.getPreferredUsername());
        assertNull(idToken.getFamilyName());
        assertNull(idToken.getGivenName());
        assertEquals("Tom Brady", idToken.getName());
        Client client = AdminClientUtil.createResteasyClient();
        try {
            Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
            UserInfo userInfo = response.readEntity(UserInfo.class);
            assertEquals("test-user@localhost", userInfo.getEmail());
            assertNull(userInfo.getPreferredUsername());
            assertEquals("Brady", userInfo.getFamilyName());
            assertEquals("Tom", userInfo.getGivenName());
            assertNull(userInfo.getName());
        } finally {
            events.expect(EventType.USER_INFO_REQUEST).session(accessTokenResponse.getSessionState()).client("test-app").assertEvent();
            client.close();
        }
        oauth.doLogout(accessTokenResponse.getRefreshToken(), "password");
        events.expectLogout(accessTokenResponse.getSessionState()).client("test-app").clearDetails().assertEvent();
        claims = ImmutableMap.of("id_token", ImmutableMap.of("test_claim", ImmutableMap.of("essential", true)), "access_token", ImmutableMap.of("email", ImmutableMap.of("essential", true), "preferred_username", ImmutableMap.of("essential", true), "family_name", ImmutableMap.of("essential", true), "given_name", ImmutableMap.of("essential", true), "name", ImmutableMap.of("essential", true)));
        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);
        oidcRequest.put(OIDCLoginProtocol.SCOPE_PARAM, "openid");
        request = new JWSBuilder().jsonContent(oidcRequest).none();
        oauth = oauth.request(request);
        oauth.doLogin("test-user@localhost", "password");
        loginEvent = events.expectLogin().assertEvent();
        accessTokenResponse = sendTokenRequestAndGetResponse(loginEvent);
        idToken = oauth.verifyIDToken(accessTokenResponse.getIdToken());
        // "email" default scope still remains
        assertEquals("test-user@localhost", idToken.getEmail());
        assertNull(idToken.getPreferredUsername());
        assertNull(idToken.getFamilyName());
        assertNull(idToken.getGivenName());
        assertNull(idToken.getName());
        client = AdminClientUtil.createResteasyClient();
        try {
            Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
            UserInfo userInfo = response.readEntity(UserInfo.class);
            assertEquals("test-user@localhost", userInfo.getEmail());
            assertNull(userInfo.getPreferredUsername());
            assertNull(userInfo.getFamilyName());
            assertNull(userInfo.getGivenName());
            assertNull(userInfo.getName());
        } finally {
            client.close();
        }
    } finally {
        // revert "profile" default client scope
        findClientResourceByClientId(adminClient.realm("test"), "test-app").addDefaultClientScope(clientScopeId);
    }
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) UserInfo(org.keycloak.representations.UserInfo) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Response(javax.ws.rs.core.Response) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ProtocolMappersResource(org.keycloak.admin.client.resource.ProtocolMappersResource) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 10 with JWSBuilder

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

the class TestingOIDCEndpointsApplicationResource method setOidcRequest.

private void setOidcRequest(Object oidcRequest, String jwaAlgorithm, String clientSecret) {
    if (!isSupportedAlgorithm(jwaAlgorithm))
        throw new BadRequestException("Unknown argument: " + jwaAlgorithm);
    if ("none".equals(jwaAlgorithm)) {
        clientData.setOidcRequest(new JWSBuilder().jsonContent(oidcRequest).none());
    } else {
        SignatureSignerContext signer;
        switch(jwaAlgorithm) {
            case Algorithm.HS256:
            case Algorithm.HS384:
            case Algorithm.HS512:
                KeyWrapper keyWrapper = new KeyWrapper();
                SecretKey secretKey = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), JavaAlgorithm.getJavaAlgorithm(jwaAlgorithm));
                keyWrapper.setSecretKey(secretKey);
                String kid = KeyUtils.createKeyId(secretKey);
                keyWrapper.setKid(kid);
                keyWrapper.setAlgorithm(jwaAlgorithm);
                keyWrapper.setUse(KeyUse.SIG);
                keyWrapper.setType(KeyType.OCT);
                signer = new MacSignatureSignerContext(keyWrapper);
                clientData.setOidcRequest(new JWSBuilder().kid(kid).jsonContent(oidcRequest).sign(signer));
                break;
            default:
                throw new BadRequestException("Unknown jwaAlgorithm: " + jwaAlgorithm);
        }
    }
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) SecretKey(javax.crypto.SecretKey) ServerECDSASignatureSignerContext(org.keycloak.crypto.ServerECDSASignatureSignerContext) MacSignatureSignerContext(org.keycloak.crypto.MacSignatureSignerContext) AsymmetricSignatureSignerContext(org.keycloak.crypto.AsymmetricSignatureSignerContext) SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) SecretKeySpec(javax.crypto.spec.SecretKeySpec) BadRequestException(javax.ws.rs.BadRequestException) MacSignatureSignerContext(org.keycloak.crypto.MacSignatureSignerContext) 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