Search in sources :

Example 21 with AccessToken

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

the class FAPICIBATest method verifyBackchannelAuthenticationTokenRequest.

private void verifyBackchannelAuthenticationTokenRequest(OAuthClient.AccessTokenResponse tokenRes, String clientId, String username) {
    assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
    events.expectAuthReqIdToToken(null, null).clearDetails().user(AssertEvents.isUUID()).client(clientId).assertEvent();
    AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
    assertThat(accessToken.getIssuedFor(), is(equalTo(clientId)));
    Assert.assertNotNull(accessToken.getCertConf().getCertThumbprint());
    RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
    assertThat(refreshToken.getIssuedFor(), is(equalTo(clientId)));
    assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
    IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
    assertThat(idToken.getPreferredUsername(), is(equalTo(username)));
    assertThat(idToken.getIssuedFor(), is(equalTo(clientId)));
    assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) AccessToken(org.keycloak.representations.AccessToken) IDToken(org.keycloak.representations.IDToken)

Example 22 with AccessToken

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

the class AccessTokenTest method testClientScope.

@Test
public void testClientScope() throws Exception {
    RealmResource realm = adminClient.realm("test");
    RoleRepresentation realmRole = new RoleRepresentation();
    realmRole.setName("realm-test-role");
    realm.roles().create(realmRole);
    realmRole = realm.roles().get("realm-test-role").toRepresentation();
    RoleRepresentation realmRole2 = new RoleRepresentation();
    realmRole2.setName("realm-test-role2");
    realm.roles().create(realmRole2);
    realmRole2 = realm.roles().get("realm-test-role2").toRepresentation();
    List<UserRepresentation> users = realm.users().search("test-user@localhost", -1, -1);
    assertEquals(1, users.size());
    UserRepresentation user = users.get(0);
    List<RoleRepresentation> addRoles = new LinkedList<>();
    addRoles.add(realmRole);
    addRoles.add(realmRole2);
    realm.users().get(user.getId()).roles().realmLevel().add(addRoles);
    ClientScopeRepresentation rep = new ClientScopeRepresentation();
    rep.setName("scope");
    rep.setProtocol("openid-connect");
    Response response = realm.clientScopes().create(rep);
    assertEquals(201, response.getStatus());
    URI scopeUri = response.getLocation();
    String clientScopeId = ApiUtil.getCreatedId(response);
    response.close();
    ClientScopeResource clientScopeResource = adminClient.proxy(ClientScopeResource.class, scopeUri);
    ProtocolMapperModel hard = HardcodedClaim.create("hard", "hard", "coded", "String", true, true);
    ProtocolMapperRepresentation mapper = ModelToRepresentation.toRepresentation(hard);
    response = clientScopeResource.getProtocolMappers().createMapper(mapper);
    assertEquals(201, response.getStatus());
    response.close();
    ClientRepresentation clientRep = ApiUtil.findClientByClientId(realm, "test-app").toRepresentation();
    realm.clients().get(clientRep.getId()).addDefaultClientScope(clientScopeId);
    clientRep.setFullScopeAllowed(false);
    realm.clients().get(clientRep.getId()).update(clientRep);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        IDToken idToken = getIdToken(tokenResponse);
        assertEquals("coded", idToken.getOtherClaims().get("hard"));
        AccessToken accessToken = getAccessToken(tokenResponse);
        assertEquals("coded", accessToken.getOtherClaims().get("hard"));
        // check zero scope for client scope
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test that scope is added
    List<RoleRepresentation> addRole1 = new LinkedList<>();
    addRole1.add(realmRole);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole1);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        // check single role in scope for client scope
        assertNotNull(accessToken.getRealmAccess());
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test combined scopes
    List<RoleRepresentation> addRole2 = new LinkedList<>();
    addRole2.add(realmRole2);
    realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().add(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        // check zero scope for client scope
        assertNotNull(accessToken.getRealmAccess());
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // remove scopes and retest
    clientScopeResource.getScopeMappings().realmLevel().remove(addRole1);
    realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().remove(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test don't use client scope scope. Add roles back to the clientScope, but they won't be available
    realm.clients().get(clientRep.getId()).removeDefaultClientScope(clientScopeId);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole1);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        assertNull(accessToken.getOtherClaims().get("hard"));
        IDToken idToken = getIdToken(tokenResponse);
        assertNull(idToken.getOtherClaims().get("hard"));
        response.close();
        client.close();
    }
    // undo mappers
    realm.users().get(user.getId()).roles().realmLevel().remove(addRoles);
    realm.roles().get(realmRole.getName()).remove();
    realm.roles().get(realmRole2.getName()).remove();
    clientScopeResource.remove();
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        IDToken idToken = getIdToken(tokenResponse);
        assertNull(idToken.getOtherClaims().get("hard"));
        AccessToken accessToken = getAccessToken(tokenResponse);
        assertNull(accessToken.getOtherClaims().get("hard"));
        response.close();
        client.close();
    }
    events.clear();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) URI(java.net.URI) LinkedList(java.util.LinkedList) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Response(javax.ws.rs.core.Response) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) AccessToken(org.keycloak.representations.AccessToken) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) IDToken(org.keycloak.representations.IDToken) WebTarget(javax.ws.rs.client.WebTarget) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UriBuilder(javax.ws.rs.core.UriBuilder) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 23 with AccessToken

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

the class AccessTokenTest method tokenRequest.

private void tokenRequest(String expectedRefreshAlg, String expectedAccessAlg, String expectedIdTokenAlg) throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(200, response.getStatusCode());
    assertEquals("Bearer", response.getTokenType());
    JWSHeader header = new JWSInput(response.getAccessToken()).getHeader();
    assertEquals(expectedAccessAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    header = new JWSInput(response.getIdToken()).getHeader();
    assertEquals(expectedIdTokenAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    header = new JWSInput(response.getRefreshToken()).getHeader();
    assertEquals(expectedRefreshAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), token.getSubject());
    assertNotEquals("test-user@localhost", token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    EventRepresentation event = events.expectCodeToToken(codeId, sessionId).assertEvent();
    assertEquals(token.getId(), event.getDetails().get(Details.TOKEN_ID));
    assertEquals(oauth.parseRefreshToken(response.getRefreshToken()).getId(), event.getDetails().get(Details.REFRESH_TOKEN_ID));
    assertEquals(sessionId, token.getSessionState());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) JWSInput(org.keycloak.jose.jws.JWSInput) JWSHeader(org.keycloak.jose.jws.JWSHeader)

Example 24 with AccessToken

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

the class AccessTokenTest method accessTokenCodeRoleMissing.

@Test
public void accessTokenCodeRoleMissing() {
    RealmResource realmResource = adminClient.realm("test");
    RoleRepresentation role = RoleBuilder.create().name("tmp-role").build();
    realmResource.roles().create(role);
    UserResource user = findUserByUsernameId(realmResource, "test-user@localhost");
    UserManager.realm(realmResource).user(user).assignRoles(role.getName());
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    realmResource.roles().deleteRole("tmp-role");
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertEquals(200, response.getStatusCode());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    Assert.assertEquals(1, token.getRealmAccess().getRoles().size());
    assertTrue(token.getRealmAccess().isUserInRole("user"));
    events.clear();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) AccessToken(org.keycloak.representations.AccessToken) UserResource(org.keycloak.admin.client.resource.UserResource) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 25 with AccessToken

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

the class AccessTokenTest method testAuthorizationNegotiateHeaderIgnored.

// KEYCLOAK-1595 Assert that public client is able to retrieve token even if header "Authorization: Negotiate something" was used (parameter client_id has preference in this case)
@Test
public void testAuthorizationNegotiateHeaderIgnored() throws Exception {
    adminClient.realm("test").clients().create(ClientBuilder.create().clientId("sample-public-client").authenticatorType("client-secret").redirectUris(oauth.getRedirectUri() + "/*").publicClient().build());
    oauth.clientId("sample-public-client");
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().client("sample-public-client").assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpPost post = new HttpPost(oauth.getAccessTokenUrl());
        List<NameValuePair> parameters = new LinkedList<>();
        parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
        parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
        parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, oauth.getRedirectUri()));
        parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, oauth.getClientId()));
        post.setHeader("Authorization", "Negotiate something-which-will-be-ignored");
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        post.setEntity(formEntity);
        OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(client.execute(post));
        Assert.assertEquals(200, response.getStatusCode());
        AccessToken token = oauth.verifyToken(response.getAccessToken());
        events.expectCodeToToken(codeId, sessionId).client("sample-public-client").assertEvent();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LinkedList(java.util.LinkedList) AccessToken(org.keycloak.representations.AccessToken) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

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