Search in sources :

Example 11 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project keycloak by keycloak.

the class ClientInitiatedAccountLinkTest method testLinkOnlyProvider.

@Test
public void testLinkOnlyProvider() throws Exception {
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    IdentityProviderRepresentation rep = realm.identityProviders().get(PARENT_IDP).toRepresentation();
    rep.setLinkOnly(true);
    realm.identityProviders().get(PARENT_IDP).update(rep);
    try {
        List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertTrue(links.isEmpty());
        UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link");
        String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
        navigateTo(linkUrl);
        Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
        // should not be on login page.  This is what we are testing
        Assert.assertFalse(driver.getPageSource().contains(PARENT_IDP));
        // now test that we can still link.
        loginPage.login("child", "password");
        Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
        loginPage.login(PARENT_USERNAME, "password");
        System.out.println("After linking: " + driver.getCurrentUrl());
        System.out.println(driver.getPageSource());
        Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
        Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
        links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertFalse(links.isEmpty());
        realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
        links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertTrue(links.isEmpty());
        logoutAll();
        System.out.println("testing link-only attack");
        navigateTo(linkUrl);
        Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
        System.out.println("login page uri is: " + driver.getCurrentUrl());
        // ok, now scrape the code from page
        String pageSource = driver.getPageSource();
        String action = ActionURIUtils.getActionURIFromPageSource(pageSource);
        System.out.println("action uri: " + action);
        Map<String, String> queryParams = ActionURIUtils.parseQueryParamsFromActionURI(action);
        System.out.println("query params: " + queryParams);
        // now try and use the code to login to remote link-only idp
        String uri = "/auth/realms/child/broker/parent-idp/login";
        uri = UriBuilder.fromUri(getAuthServerContextRoot()).path(uri).queryParam(LoginActionsService.SESSION_CODE, queryParams.get(LoginActionsService.SESSION_CODE)).queryParam(Constants.CLIENT_ID, queryParams.get(Constants.CLIENT_ID)).queryParam(Constants.TAB_ID, queryParams.get(Constants.TAB_ID)).build().toString();
        System.out.println("hack uri: " + uri);
        navigateTo(uri);
        Assert.assertTrue(driver.getPageSource().contains("Could not send authentication request to identity provider."));
    } finally {
        rep.setLinkOnly(false);
        realm.identityProviders().get(PARENT_IDP).update(rep);
    }
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 12 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project keycloak by keycloak.

the class AccessTokenTest method testGrantAccessToken.

@Test
public void testGrantAccessToken() throws Exception {
    Client client = AdminClientUtil.createResteasyClient();
    UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
    URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
    WebTarget grantTarget = client.target(grantUri);
    {
        // test checkSsl
        {
            RealmResource realmsResource = adminClient.realm("test");
            RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
            realmRepresentation.setSslRequired(SslRequired.ALL.toString());
            realmsResource.update(realmRepresentation);
        }
        Response response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(AUTH_SERVER_SSL_REQUIRED ? 200 : 403, response.getStatus());
        response.close();
        {
            RealmResource realmsResource = realmsResouce().realm("test");
            RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
            realmRepresentation.setSslRequired(SslRequired.EXTERNAL.toString());
            realmsResource.update(realmRepresentation);
        }
    }
    {
        // test null username
        String header = BasicAuthHelper.createHeader("test-app", "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("password", "password");
        Response response = grantTarget.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
        assertEquals(401, response.getStatus());
        response.close();
    }
    {
        // test no password
        String header = BasicAuthHelper.createHeader("test-app", "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "test-user@localhost");
        Response response = grantTarget.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
        assertEquals(401, response.getStatus());
        response.close();
    }
    {
        // test invalid password
        String header = BasicAuthHelper.createHeader("test-app", "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "test-user@localhost");
        form.param("password", "invalid");
        Response response = grantTarget.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
        assertEquals(401, response.getStatus());
        response.close();
    }
    {
        // test no password
        String header = BasicAuthHelper.createHeader("test-app", "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "test-user@localhost");
        Response response = grantTarget.request().header(HttpHeaders.AUTHORIZATION, header).post(Entity.form(form));
        assertEquals(401, response.getStatus());
        response.close();
    }
    {
        // test bearer-only
        {
            ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = clientResource.toRepresentation();
            clientRepresentation.setBearerOnly(true);
            clientResource.update(clientRepresentation);
        }
        Response response = executeGrantAccessTokenRequest(grantTarget);
        // 401 because the client is now a bearer without a secret
        assertEquals(401, response.getStatus());
        response.close();
        {
            ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = clientResource.toRepresentation();
            clientRepresentation.setBearerOnly(false);
            // reset to the old secret
            clientRepresentation.setSecret("password");
            clientResource.update(clientRepresentation);
        }
    }
    {
        // test realm disabled
        {
            RealmResource realmsResource = realmsResouce().realm("test");
            RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
            realmRepresentation.setEnabled(false);
            realmsResource.update(realmRepresentation);
        }
        Response response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(403, response.getStatus());
        response.close();
        {
            RealmResource realmsResource = realmsResouce().realm("test");
            RealmRepresentation realmRepresentation = realmsResource.toRepresentation();
            realmRepresentation.setEnabled(true);
            realmsResource.update(realmRepresentation);
        }
    }
    {
        // test application disabled
        {
            ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = clientResource.toRepresentation();
            clientRepresentation.setEnabled(false);
            clientResource.update(clientRepresentation);
        }
        Response response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(400, response.getStatus());
        response.close();
        {
            ClientResource clientResource = findClientByClientId(adminClient.realm("test"), "test-app");
            ClientRepresentation clientRepresentation = clientResource.toRepresentation();
            clientRepresentation.setEnabled(true);
            clientResource.update(clientRepresentation);
        }
    }
    {
        // test user action required
        {
            UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
            UserRepresentation userRepresentation = userResource.toRepresentation();
            userRepresentation.getRequiredActions().add(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
            userResource.update(userRepresentation);
        }
        // good password is 400 => Account is not fully set up
        try (Response response = executeGrantAccessTokenRequest(grantTarget)) {
            assertEquals(400, response.getStatus());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.readEntity(String.class));
            assertEquals("invalid_grant", jsonNode.get("error").asText());
            assertEquals("Account is not fully set up", jsonNode.get("error_description").asText());
        }
        // wrong password is 401 => Invalid user credentials
        try (Response response = executeGrantAccessTokenRequestWrongPassword(grantTarget)) {
            assertEquals(401, response.getStatus());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.readEntity(String.class));
            assertEquals("invalid_grant", jsonNode.get("error").asText());
            assertEquals("Invalid user credentials", jsonNode.get("error_description").asText());
        }
        {
            UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
            UserRepresentation userRepresentation = userResource.toRepresentation();
            userRepresentation.getRequiredActions().remove(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
            userResource.update(userRepresentation);
        }
    }
    {
        // test user disabled
        {
            UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
            UserRepresentation userRepresentation = userResource.toRepresentation();
            userRepresentation.setEnabled(false);
            userResource.update(userRepresentation);
        }
        Response response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(400, response.getStatus());
        response.close();
        {
            UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
            UserRepresentation userRepresentation = userResource.toRepresentation();
            userRepresentation.setEnabled(true);
            userResource.update(userRepresentation);
        }
    }
    {
        Response response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        response.close();
    }
    client.close();
    events.clear();
}
Also used : Form(javax.ws.rs.core.Form) RealmResource(org.keycloak.admin.client.resource.RealmResource) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) UserResource(org.keycloak.admin.client.resource.UserResource) JsonNode(com.fasterxml.jackson.databind.JsonNode) URI(java.net.URI) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Response(javax.ws.rs.core.Response) ClientResource(org.keycloak.admin.client.resource.ClientResource) 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) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 13 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project keycloak by keycloak.

the class AccessTokenTest method expiration.

// KEYCLOAK-4215
@Test
public void expiration() throws Exception {
    int sessionMax = (int) TimeUnit.MINUTES.toSeconds(30);
    int sessionIdle = (int) TimeUnit.MINUTES.toSeconds(30);
    int tokenLifespan = (int) TimeUnit.MINUTES.toSeconds(5);
    RealmResource realm = adminClient.realm("test");
    RealmRepresentation rep = realm.toRepresentation();
    Integer originalSessionMax = rep.getSsoSessionMaxLifespan();
    rep.setSsoSessionMaxLifespan(sessionMax);
    realm.update(rep);
    try {
        oauth.doLogin("test-user@localhost", "password");
        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        assertEquals(200, response.getStatusCode());
        // Assert refresh expiration equals session idle
        assertExpiration(response.getRefreshExpiresIn(), sessionIdle);
        // Assert token expiration equals token lifespan
        assertExpiration(response.getExpiresIn(), tokenLifespan);
        setTimeOffset(sessionMax - 60);
        response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "password");
        assertEquals(200, response.getStatusCode());
        // Assert expiration equals session expiration
        assertExpiration(response.getRefreshExpiresIn(), 60);
        assertExpiration(response.getExpiresIn(), 60);
    } finally {
        rep.setSsoSessionMaxLifespan(originalSessionMax);
        realm.update(rep);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 14 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource 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 15 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource 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)

Aggregations

RealmResource (org.keycloak.admin.client.resource.RealmResource)263 Test (org.junit.Test)190 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)67 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)61 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)58 Response (javax.ws.rs.core.Response)55 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)48 ClientResource (org.keycloak.admin.client.resource.ClientResource)39 OAuthClient (org.keycloak.testsuite.util.OAuthClient)37 GroupRepresentation (org.keycloak.representations.idm.GroupRepresentation)36 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)34 Before (org.junit.Before)31 UserResource (org.keycloak.admin.client.resource.UserResource)30 IdentityProviderRepresentation (org.keycloak.representations.idm.IdentityProviderRepresentation)25 List (java.util.List)19 LinkedList (java.util.LinkedList)16 ClientScopeRepresentation (org.keycloak.representations.idm.ClientScopeRepresentation)16 VerifyProfileTest (org.keycloak.testsuite.forms.VerifyProfileTest)14 ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)13 AccessToken (org.keycloak.representations.AccessToken)12