Search in sources :

Example 1 with FederatedIdentityRepresentation

use of org.keycloak.representations.idm.FederatedIdentityRepresentation in project keycloak by keycloak.

the class UserResource method getUser.

/**
 * Get representation of the user
 *
 * @return
 */
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public UserRepresentation getUser() {
    auth.users().requireView(user);
    UserRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, user);
    if (realm.isIdentityFederationEnabled()) {
        List<FederatedIdentityRepresentation> reps = getFederatedIdentities(user).collect(Collectors.toList());
        rep.setFederatedIdentities(reps);
    }
    if (session.getProvider(BruteForceProtector.class).isTemporarilyDisabled(session, realm, user)) {
        rep.setEnabled(false);
    }
    rep.setAccess(auth.users().getAccess(user));
    UserProfileProvider provider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = provider.create(USER_API, user);
    Map<String, List<String>> readableAttributes = profile.getAttributes().getReadable(false);
    if (rep.getAttributes() != null) {
        rep.setAttributes(readableAttributes);
    }
    return rep;
}
Also used : UserProfile(org.keycloak.userprofile.UserProfile) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 2 with FederatedIdentityRepresentation

use of org.keycloak.representations.idm.FederatedIdentityRepresentation in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLinkNoTokenStore.

@Test
@UncaughtServerErrorExpected
public void testAccountLinkNoTokenStore() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOffTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    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();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    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"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    logoutAll();
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 3 with FederatedIdentityRepresentation

use of org.keycloak.representations.idm.FederatedIdentityRepresentation in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLink.

@Test
@UncaughtServerErrorExpected
public void testAccountLink() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOnTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    String servletUri = appPage.getInjectedUrl().toString();
    UriBuilder linkBuilder = UriBuilder.fromUri(servletUri).path("link");
    String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    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"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    // do exchange
    String accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
    Client httpClient = AdminClientUtil.createResteasyClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).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_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String externalToken = tokenResponse.getToken();
        Assert.assertNotNull(externalToken);
        Assert.assertTrue(tokenResponse.getExpiresIn() > 0);
        setTimeOffset((int) tokenResponse.getExpiresIn() + 1);
        // test that token refresh happens
        // get access token again because we may have timed out
        accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).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_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        // test direct exchange
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-exchanger", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "child").param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        logoutAll();
        realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
        links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertTrue(links.isEmpty());
    } finally {
        httpClient.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) RealmResource(org.keycloak.admin.client.resource.RealmResource) WebTarget(javax.ws.rs.client.WebTarget) UriBuilder(javax.ws.rs.core.UriBuilder) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 4 with FederatedIdentityRepresentation

use of org.keycloak.representations.idm.FederatedIdentityRepresentation in project keycloak by keycloak.

the class ClientInitiatedAccountLinkTest method testAccountLink.

@Test
public void testAccountLink() throws Exception {
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    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();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    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"));
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, "client-linking", "password");
    Assert.assertNotNull(response.getAccessToken());
    Assert.assertNull(response.getError());
    Client httpClient = AdminClientUtil.createResteasyClient();
    String firstToken = getToken(response, httpClient);
    Assert.assertNotNull(firstToken);
    navigateTo(linkUrl);
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    String nextToken = getToken(response, httpClient);
    Assert.assertNotNull(nextToken);
    Assert.assertNotEquals(firstToken, nextToken);
    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();
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) UriBuilder(javax.ws.rs.core.UriBuilder) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 5 with FederatedIdentityRepresentation

use of org.keycloak.representations.idm.FederatedIdentityRepresentation in project keycloak by keycloak.

the class ClientInitiatedAccountLinkTest method testErrorConditions.

@Test
public void testErrorConditions() throws Exception {
    String helloUrl = appPage.getUriBuilder().clone().path("hello").build().toASCIIString();
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    ClientRepresentation client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
    UriBuilder redirectUri = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link").queryParam("response", "true");
    UriBuilder directLinking = UriBuilder.fromUri(getAuthServerContextRoot() + "/auth").path("realms/child/broker/{provider}/link").queryParam("client_id", "client-linking").queryParam("redirect_uri", redirectUri.build()).queryParam("hash", Base64Url.encode("crap".getBytes())).queryParam("nonce", UUID.randomUUID().toString());
    String linkUrl = directLinking.build(PARENT_IDP).toString();
    // test not logged in
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_logged_in"));
    logoutAll();
    // now log in
    navigateTo(helloUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(helloUrl));
    Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
    // now test CSRF with bad hash.
    navigateTo(linkUrl);
    Assert.assertTrue(driver.getPageSource().contains("We are sorry..."));
    logoutAll();
    // now log in again with client that does not have scope
    String accountId = adminClient.realms().realm(CHILD_IDP).clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId();
    RoleRepresentation manageAccount = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT).toRepresentation();
    RoleRepresentation manageLinks = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT_LINKS).toRepresentation();
    RoleRepresentation userRole = adminClient.realms().realm(CHILD_IDP).roles().get("user").toRepresentation();
    client.setFullScopeAllowed(false);
    ClientResource clientResource = adminClient.realms().realm(CHILD_IDP).clients().get(client.getId());
    clientResource.update(client);
    List<RoleRepresentation> roles = new LinkedList<>();
    roles.add(userRole);
    clientResource.getScopeMappings().realmLevel().add(roles);
    navigateTo(helloUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(helloUrl));
    Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
    UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link");
    String clientLinkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(driver.getCurrentUrl().contains("error=not_allowed"));
    logoutAll();
    // add MANAGE_ACCOUNT_LINKS scope should pass.
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    roles = new LinkedList<>();
    roles.add(manageLinks);
    clientResource.getScopeMappings().clientLevel(accountId).add(roles);
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    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());
    clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
    logoutAll();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
    logoutAll();
    // add MANAGE_ACCOUNT scope should pass
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    roles = new LinkedList<>();
    roles.add(manageAccount);
    clientResource.getScopeMappings().clientLevel(accountId).add(roles);
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    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());
    clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
    logoutAll();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
    logoutAll();
    // undo fullScopeAllowed
    client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
    client.setFullScopeAllowed(true);
    clientResource.update(client);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    logoutAll();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) ClientResource(org.keycloak.admin.client.resource.ClientResource) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Aggregations

FederatedIdentityRepresentation (org.keycloak.representations.idm.FederatedIdentityRepresentation)30 Test (org.junit.Test)18 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)12 RealmResource (org.keycloak.admin.client.resource.RealmResource)9 LinkedList (java.util.LinkedList)7 List (java.util.List)7 UriBuilder (javax.ws.rs.core.UriBuilder)6 ArrayList (java.util.ArrayList)5 AbstractServletsAdapterTest (org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)5 Map (java.util.Map)4 UserResource (org.keycloak.admin.client.resource.UserResource)4 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)4 CredentialRepresentation (org.keycloak.representations.idm.CredentialRepresentation)4 IdentityProviderRepresentation (org.keycloak.representations.idm.IdentityProviderRepresentation)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Response (javax.ws.rs.core.Response)3 UsersResource (org.keycloak.admin.client.resource.UsersResource)3 MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)3 UserConsentRepresentation (org.keycloak.representations.idm.UserConsentRepresentation)3