Search in sources :

Example 81 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class AdminSignatureAlgorithmTest method changeRealmTokenAlgorithm.

@Test
public void changeRealmTokenAlgorithm() throws Exception {
    String defaultSignatureAlgorithm = adminClient.realm("master").toRepresentation().getDefaultSignatureAlgorithm();
    TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256);
    try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString())) {
        AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class);
        assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name());
        assertNotNull(adminClient.realms().findAll());
        String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami";
        JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson();
        assertNotNull(jsonNode.get("realm"));
        assertNotNull(jsonNode.get("userId"));
    } finally {
        TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, defaultSignatureAlgorithm);
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) JsonNode(com.fasterxml.jackson.databind.JsonNode) Keycloak(org.keycloak.admin.client.Keycloak) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 82 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class FAPI1Test method testFAPIAdvancedLoginWithMTLS.

@Test
public void testFAPIAdvancedLoginWithMTLS() throws Exception {
    // Set "advanced" policy
    setupPolicyFAPIAdvancedForAllClient();
    // Register client with X509
    String clientUUID = createClientByAdmin("foo", (ClientRepresentation clientRep) -> {
        clientRep.setClientAuthenticatorType(X509ClientAuthenticator.PROVIDER_ID);
        clientRep.setImplicitFlowEnabled(true);
        OIDCAdvancedConfigWrapper clientConfig = OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep);
        clientConfig.setRequestUris(Collections.singletonList(TestApplicationResourceUrls.clientRequestUri()));
        clientConfig.setTlsClientAuthSubjectDn("EMAILADDRESS=contact@keycloak.org, CN=Keycloak Intermediate CA, OU=Keycloak, O=Red Hat, ST=MA, C=US");
    });
    ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(clientUUID);
    ClientRepresentation client = clientResource.toRepresentation();
    assertEquals(X509ClientAuthenticator.PROVIDER_ID, client.getClientAuthenticatorType());
    // Check nonce and redirectUri
    oauth.clientId("foo");
    checkNonceAndStateForCurrentClientDuringLogin();
    checkRedirectUriForCurrentClientDuringLogin();
    // Check login request object required
    oauth.openLoginForm();
    assertRedirectedToClientWithError(OAuthErrorException.INVALID_REQUEST, false, "Missing parameter: 'request' or 'request_uri'");
    // Set request object and correct responseType
    TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject requestObject = createValidRequestObjectForSecureRequestObjectExecutor("foo");
    // Nonce from method "checkNonceAndStateForCurrentClientDuringLogin()"
    requestObject.setNonce("123456");
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
    requestObject.setResponseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
    registerRequestObject(requestObject, "foo", org.keycloak.jose.jws.Algorithm.PS256, true);
    oauth.openLoginForm();
    loginPage.assertCurrent();
    String code = loginUserAndGetCode("foo", true);
    // Check token not present in the AuthorizationResponse. Check ID Token present, but used as detached signature
    Assert.assertNull(getParameterFromUrl(OAuth2Constants.ACCESS_TOKEN, true));
    String idTokenParam = getParameterFromUrl(OAuth2Constants.ID_TOKEN, true);
    assertIDTokenAsDetachedSignature(idTokenParam, code);
    // Check HoK required
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, null);
    assertSuccessfulTokenResponse(tokenResponse);
    AccessToken accessToken = oauth.verifyToken(tokenResponse.getAccessToken());
    Assert.assertNotNull(accessToken.getCertConf().getCertThumbprint());
    // Logout and remove consent of the user for next logins
    logoutUserAndRevokeConsent("foo");
}
Also used : OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) TestingOIDCEndpointsApplicationResource(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 83 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class ClientAuthSignedJWTTest method testDirectGrantRequestSuccess.

private void testDirectGrantRequestSuccess(String algorithm) throws Exception {
    ClientRepresentation clientRepresentation = app2;
    ClientResource clientResource = getClient(testRealm.getRealm(), clientRepresentation.getId());
    clientRepresentation = clientResource.toRepresentation();
    try {
        // setup Jwks
        KeyPair keyPair = setupJwksUrl(algorithm, clientRepresentation, clientResource);
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        // test
        oauth.clientId("client2");
        OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest("test-user@localhost", "password", createSignedRequestToken("client2", getRealmInfoUrl(), privateKey, publicKey, algorithm));
        assertEquals(200, response.getStatusCode());
        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
        RefreshToken refreshToken = oauth.parseRefreshToken(response.getRefreshToken());
        events.expectLogin().client("client2").session(accessToken.getSessionState()).detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, "test-user@localhost").detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID).removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT).assertEvent();
    } finally {
        // Revert jwks_url settings
        revertJwksUriSettings(clientRepresentation, clientResource);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) PublicKey(java.security.PublicKey) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 84 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class ClientAuthSignedJWTTest method testAssertionReuse.

@Test
public void testAssertionReuse() throws Exception {
    String clientJwt = getClient1SignedJWT();
    OAuthClient.AccessTokenResponse response = doClientCredentialsGrantRequest(clientJwt);
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    Assert.assertNotNull(accessToken);
    Assert.assertNull(response.getError());
    // 2nd attempt to reuse same JWT should fail
    response = doClientCredentialsGrantRequest(clientJwt);
    assertEquals(400, response.getStatusCode());
    assertEquals(OAuthErrorException.INVALID_CLIENT, response.getError());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 85 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class ClientTokenExchangeTest method testImpersonation.

@Test
@UncaughtServerErrorExpected
public void testImpersonation() throws Exception {
    testingClient.server().run(ClientTokenExchangeTest::setupRealm);
    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    Client httpClient = AdminClientUtil.createResteasyClient();
    WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT).path("/realms").path(TEST).path("protocol/openid-connect/token");
    System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = tokenResponse.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));
    // client-exchanger can impersonate from token "user" to user "impersonated-user"
    {
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("client-exchanger", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user")));
        org.junit.Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String exchangedTokenString = accessTokenResponse.getToken();
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class);
        AccessToken exchangedToken = verifier.parse().getToken();
        Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor());
        Assert.assertNull(exchangedToken.getAudience());
        Assert.assertEquals("impersonated-user", exchangedToken.getPreferredUsername());
        Assert.assertNull(exchangedToken.getRealmAccess());
        Object impersonatorRaw = exchangedToken.getOtherClaims().get("impersonator");
        Assert.assertThat(impersonatorRaw, instanceOf(Map.class));
        Map impersonatorClaim = (Map) impersonatorRaw;
        Assert.assertEquals(token.getSubject(), impersonatorClaim.get("id"));
        Assert.assertEquals("user", impersonatorClaim.get("username"));
    }
    // client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client
    {
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("client-exchanger", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user").param(OAuth2Constants.AUDIENCE, "target")));
        org.junit.Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String exchangedTokenString = accessTokenResponse.getToken();
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(exchangedTokenString, AccessToken.class);
        AccessToken exchangedToken = verifier.parse().getToken();
        Assert.assertEquals("client-exchanger", exchangedToken.getIssuedFor());
        Assert.assertEquals("target", exchangedToken.getAudience()[0]);
        Assert.assertEquals(exchangedToken.getPreferredUsername(), "impersonated-user");
        Assert.assertTrue(exchangedToken.getRealmAccess().isUserInRole("example"));
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) Form(javax.ws.rs.core.Form) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) AccessToken(org.keycloak.representations.AccessToken) TokenVerifier(org.keycloak.TokenVerifier) WebTarget(javax.ws.rs.client.WebTarget) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Map(java.util.Map) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Aggregations

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13