Search in sources :

Example 76 with ProtocolMapperRepresentation

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

the class ExportImportUtil method testRealmDefaultClientScopes.

public static void testRealmDefaultClientScopes(RealmResource realm) {
    // Assert built-in scopes were created in realm
    List<ClientScopeRepresentation> clientScopes = realm.clientScopes().findAll();
    Map<String, ClientScopeRepresentation> clientScopesMap = clientScopes.stream().collect(Collectors.toMap(ClientScopeRepresentation::getName, Function.identity()));
    assertThat(clientScopesMap.keySet(), Matchers.hasItems(OAuth2Constants.SCOPE_PROFILE, OAuth2Constants.SCOPE_EMAIL, OAuth2Constants.SCOPE_ADDRESS, OAuth2Constants.SCOPE_PHONE, OAuth2Constants.OFFLINE_ACCESS, OIDCLoginProtocolFactory.ROLES_SCOPE, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE, OIDCLoginProtocolFactory.MICROPROFILE_JWT_SCOPE, SamlProtocolFactory.SCOPE_ROLE_LIST));
    // Check content of some client scopes
    Map<String, ProtocolMapperRepresentation> protocolMappers = clientScopesMap.get(OAuth2Constants.SCOPE_EMAIL).getProtocolMappers().stream().collect(Collectors.toMap(protocolMapper -> protocolMapper.getName(), protocolMapper -> protocolMapper));
    org.keycloak.testsuite.Assert.assertNames(protocolMappers.keySet(), OIDCLoginProtocolFactory.EMAIL, OIDCLoginProtocolFactory.EMAIL_VERIFIED);
    ClientScopeRepresentation offlineScope = clientScopesMap.get(OAuth2Constants.OFFLINE_ACCESS);
    org.keycloak.testsuite.Assert.assertTrue(offlineScope.getProtocolMappers() == null || offlineScope.getProtocolMappers().isEmpty());
    List<RoleRepresentation> offlineRoleScopes = realm.clientScopes().get(offlineScope.getId()).getScopeMappings().realmLevel().listAll();
    org.keycloak.testsuite.Assert.assertNames(offlineRoleScopes, OAuth2Constants.OFFLINE_ACCESS);
    // Check default client scopes and optional client scopes expected
    Set<String> defaultClientScopes = realm.getDefaultDefaultClientScopes().stream().map(ClientScopeRepresentation::getName).collect(Collectors.toSet());
    assertThat(defaultClientScopes, Matchers.hasItems(OAuth2Constants.SCOPE_PROFILE, OAuth2Constants.SCOPE_EMAIL, OIDCLoginProtocolFactory.ROLES_SCOPE, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE));
    Set<String> optionalClientScopes = realm.getDefaultOptionalClientScopes().stream().map(ClientScopeRepresentation::getName).collect(Collectors.toSet());
    assertThat(optionalClientScopes, Matchers.hasItems(OAuth2Constants.SCOPE_ADDRESS, OAuth2Constants.SCOPE_PHONE, OAuth2Constants.OFFLINE_ACCESS, OIDCLoginProtocolFactory.MICROPROFILE_JWT_SCOPE));
}
Also used : ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) FullNameLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) DefaultAuthenticationFlows(org.keycloak.models.utils.DefaultAuthenticationFlows) LDAPConstants(org.keycloak.models.LDAPConstants) Assert.assertThat(org.junit.Assert.assertThat) Map(java.util.Map) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) OIDCLoginProtocolFactory(org.keycloak.protocol.oidc.OIDCLoginProtocolFactory) PasswordCredentialData(org.keycloak.models.credential.dto.PasswordCredentialData) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) SamlProtocolFactory(org.keycloak.protocol.saml.SamlProtocolFactory) Collectors(java.util.stream.Collectors) Keycloak(org.keycloak.admin.client.Keycloak) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) List(java.util.List) ClientMappingsRepresentation(org.keycloak.representations.idm.ClientMappingsRepresentation) RealmRepUtil(org.keycloak.testsuite.util.RealmRepUtil) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) OAuth2Constants(org.keycloak.OAuth2Constants) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) Profile(org.keycloak.common.Profile) Constants(org.keycloak.models.Constants) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserFederationProviderRepresentation(org.keycloak.representations.idm.UserFederationProviderRepresentation) AuthenticationFlowRepresentation(org.keycloak.representations.idm.AuthenticationFlowRepresentation) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) UserResource(org.keycloak.admin.client.resource.UserResource) LinkedList(java.util.LinkedList) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ProfileAssume(org.keycloak.testsuite.ProfileAssume) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) OIDCAttributeMapperHelper(org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) KerberosConstants(org.keycloak.common.constants.KerberosConstants) UserStorageProvider(org.keycloak.storage.UserStorageProvider) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) KeycloakTestingClient(org.keycloak.testsuite.client.KeycloakTestingClient) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) JsonSerialization(org.keycloak.util.JsonSerialization) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) Matcher(org.hamcrest.Matcher) UserSessionNoteMapper(org.keycloak.protocol.oidc.mappers.UserSessionNoteMapper) Assert(org.junit.Assert) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation)

Example 77 with ProtocolMapperRepresentation

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

the class ExportImportUtil method assertDataImportedInRealm.

// In the old testsuite, this method exists as a public method of ImportTest from the model package.
// However, model package is not ready to be migrated yet.
public static void assertDataImportedInRealm(Keycloak adminClient, KeycloakTestingClient testingClient, RealmRepresentation realm) throws IOException {
    Assert.assertTrue(realm.isVerifyEmail());
    Assert.assertEquals((Integer) 3600000, realm.getOfflineSessionIdleTimeout());
    Assert.assertEquals((Integer) 1500, realm.getAccessTokenLifespanForImplicitFlow());
    Assert.assertEquals((Integer) 1800, realm.getSsoSessionIdleTimeout());
    Assert.assertEquals((Integer) 36000, realm.getSsoSessionMaxLifespan());
    Assert.assertEquals((Integer) 3600, realm.getSsoSessionIdleTimeoutRememberMe());
    Assert.assertEquals((Integer) 172800, realm.getSsoSessionMaxLifespanRememberMe());
    Set<String> creds = realm.getRequiredCredentials();
    Assert.assertEquals(1, creds.size());
    String cred = (String) creds.iterator().next();
    Assert.assertEquals("password", cred);
    RealmResource realmRsc = adminClient.realm(realm.getRealm());
    /* See KEYCLOAK-3104*/
    UserRepresentation user = findByUsername(realmRsc, "loginclient");
    Assert.assertNotNull(user);
    UserResource userRsc = realmRsc.users().get(user.getId());
    Assert.assertEquals(0, userRsc.getFederatedIdentity().size());
    List<ClientRepresentation> resources = realmRsc.clients().findAll();
    Assert.assertEquals(10, resources.size());
    // Test applications imported
    ClientRepresentation application = ApiUtil.findClientByClientId(realmRsc, "Application").toRepresentation();
    ClientRepresentation otherApp = ApiUtil.findClientByClientId(realmRsc, "OtherApp").toRepresentation();
    ClientRepresentation accountApp = ApiUtil.findClientByClientId(realmRsc, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).toRepresentation();
    ClientRepresentation testAppAuthzApp = ApiUtil.findClientByClientId(realmRsc, "test-app-authz").toRepresentation();
    ClientResource nonExisting = ApiUtil.findClientByClientId(realmRsc, "NonExisting");
    Assert.assertNotNull(application);
    Assert.assertNotNull(otherApp);
    Assert.assertNull(nonExisting);
    List<ClientRepresentation> clients = realmRsc.clients().findAll();
    Assert.assertEquals(10, clients.size());
    Assert.assertTrue(hasClient(clients, application));
    Assert.assertTrue(hasClient(clients, otherApp));
    Assert.assertTrue(hasClient(clients, accountApp));
    Assert.assertEquals("Applicationn", application.getName());
    Assert.assertEquals((Integer) 50, application.getNodeReRegistrationTimeout());
    Map<String, Integer> appRegisteredNodes = application.getRegisteredNodes();
    Assert.assertEquals(2, appRegisteredNodes.size());
    Assert.assertTrue(10 == appRegisteredNodes.get("node1"));
    Assert.assertTrue(20 == appRegisteredNodes.get("172.10.15.20"));
    // test clientAuthenticatorType
    Assert.assertEquals("client-secret", application.getClientAuthenticatorType());
    Assert.assertEquals("client-jwt", otherApp.getClientAuthenticatorType());
    // test authenticationFlowBindingOverrides
    Map<String, String> flowMap = otherApp.getAuthenticationFlowBindingOverrides();
    Assert.assertNotNull(flowMap);
    Assert.assertEquals(1, flowMap.size());
    Assert.assertTrue(flowMap.containsKey("browser"));
    // if the authentication flows were correctly imported there must be a flow whose id matches the one in the authenticationFlowBindingOverrides
    AuthenticationFlowRepresentation flowRep = realmRsc.flows().getFlow(flowMap.get("browser"));
    Assert.assertNotNull(flowRep);
    Assert.assertEquals("browser", flowRep.getAlias());
    // Test finding applications by ID
    Assert.assertNull(ApiUtil.findClientResourceById(realmRsc, "982734"));
    Assert.assertEquals(application.getId(), ApiUtil.findClientResourceById(realmRsc, application.getId()).toRepresentation().getId());
    // Test role mappings
    UserRepresentation admin = findByUsername(realmRsc, "admin");
    // user without creation timestamp in import
    Assert.assertNull(admin.getCreatedTimestamp());
    Set<RoleRepresentation> allRoles = allRoles(realmRsc, admin);
    Assert.assertEquals(3, allRoles.size());
    Assert.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "admin")));
    Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-admin")));
    Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin")));
    UserRepresentation wburke = findByUsername(realmRsc, "wburke");
    // user with creation timestamp in import
    Assert.assertEquals(new Long(123654), wburke.getCreatedTimestamp());
    allRoles = allRoles(realmRsc, wburke);
    Assert.assertEquals(2, allRoles.size());
    Assert.assertFalse(containsRole(allRoles, findRealmRole(realmRsc, "admin")));
    Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, application.getId(), "app-user")));
    Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user")));
    Assert.assertNull(realmRsc.users().get(wburke.getId()).roles().getAll().getRealmMappings());
    Assert.assertEquals((Object) 159, wburke.getNotBefore());
    UserRepresentation loginclient = findByUsername(realmRsc, "loginclient");
    // user with creation timestamp as string in import
    Assert.assertEquals(new Long(123655), loginclient.getCreatedTimestamp());
    UserRepresentation hashedPasswordUser = findByUsername(realmRsc, "hashedpassworduser");
    CredentialRepresentation password = realmRsc.users().get(hashedPasswordUser.getId()).credentials().stream().filter(credential -> PasswordCredentialModel.TYPE.equals(credential.getType())).findFirst().get();
    PasswordCredentialData credentialData = JsonSerialization.readValue(password.getCredentialData(), PasswordCredentialData.class);
    Assert.assertEquals(1234, credentialData.getHashIterations());
    List<RoleRepresentation> realmRoles = realmRolesForUser(realmRsc, admin);
    Assert.assertEquals(1, realmRoles.size());
    Assert.assertEquals("admin", realmRoles.iterator().next().getName());
    List<RoleRepresentation> appRoles = clientRolesForUser(realmRsc, application, admin);
    Assert.assertEquals(1, appRoles.size());
    Assert.assertEquals("app-admin", appRoles.iterator().next().getName());
    // Test attributes
    Map<String, List<String>> attrs = wburke.getAttributes();
    Assert.assertEquals(1, attrs.size());
    List<String> attrVals = attrs.get("old-email");
    Assert.assertEquals(1, attrVals.size());
    Assert.assertEquals("bburke@redhat.com", attrVals.get(0));
    attrs = admin.getAttributes();
    Assert.assertEquals(2, attrs.size());
    attrVals = attrs.get("key1");
    Assert.assertEquals(1, attrVals.size());
    Assert.assertEquals("val1", attrVals.get(0));
    attrVals = attrs.get("key2");
    Assert.assertEquals(2, attrVals.size());
    Assert.assertTrue(attrVals.contains("val21") && attrVals.contains("val22"));
    // Test client
    ClientResource oauthClient = ApiUtil.findClientResourceByClientId(realmRsc, "oauthclient");
    ClientRepresentation oauthClientRep = oauthClient.toRepresentation();
    Assert.assertEquals("clientpassword", oauthClient.getSecret().getValue());
    Assert.assertTrue(oauthClientRep.isEnabled());
    Assert.assertNotNull(oauthClientRep);
    // Test scope relationship
    Set<RoleRepresentation> allScopes = allScopeMappings(oauthClient);
    Assert.assertEquals(2, allScopes.size());
    Assert.assertTrue(containsRole(allScopes, findRealmRole(realmRsc, "admin")));
    Assert.assertTrue(containsRole(allScopes, findClientRole(realmRsc, application.getId(), "app-user")));
    List<RoleRepresentation> realmScopes = realmScopeMappings(oauthClient);
    Assert.assertTrue(containsRole(realmScopes, findRealmRole(realmRsc, "admin")));
    List<RoleRepresentation> appScopes = clientScopeMappings(oauthClient);
    Assert.assertTrue(containsRole(appScopes, findClientRole(realmRsc, application.getId(), "app-user")));
    // Test social linking
    UserResource socialUser = realmRsc.users().get(findByUsername(realmRsc, "mySocialUser").getId());
    List<FederatedIdentityRepresentation> socialLinks = socialUser.getFederatedIdentity();
    Assert.assertEquals(3, socialLinks.size());
    boolean facebookFound = false;
    boolean googleFound = false;
    boolean twitterFound = false;
    FederatedIdentityRepresentation facebookIdentityRep = null;
    for (FederatedIdentityRepresentation federatedIdentityRep : socialLinks) {
        if ("facebook1".equals(federatedIdentityRep.getIdentityProvider())) {
            facebookFound = true;
            facebookIdentityRep = federatedIdentityRep;
            Assert.assertEquals("facebook1", federatedIdentityRep.getUserId());
            Assert.assertEquals("fbuser1", federatedIdentityRep.getUserName());
        } else if ("google1".equals(federatedIdentityRep.getIdentityProvider())) {
            googleFound = true;
            Assert.assertEquals("google1", federatedIdentityRep.getUserId());
            Assert.assertEquals("mysocialuser@gmail.com", federatedIdentityRep.getUserName());
        } else if ("twitter1".equals(federatedIdentityRep.getIdentityProvider())) {
            twitterFound = true;
            Assert.assertEquals("twitter1", federatedIdentityRep.getUserId());
            Assert.assertEquals("twuser1", federatedIdentityRep.getUserName());
        }
    }
    Assert.assertTrue(facebookFound && twitterFound && googleFound);
    UserRepresentation foundSocialUser = testingClient.testing().getUserByFederatedIdentity(realm.getRealm(), "facebook1", "facebook1", "fbuser1");
    Assert.assertEquals(foundSocialUser.getUsername(), socialUser.toRepresentation().getUsername());
    Assert.assertNull(testingClient.testing().getUserByFederatedIdentity(realm.getRealm(), "facebook", "not-existing", "not-existing"));
    Assert.assertEquals("facebook1", facebookIdentityRep.getUserId());
    Assert.assertEquals("fbuser1", facebookIdentityRep.getUserName());
    Assert.assertEquals("facebook1", facebookIdentityRep.getIdentityProvider());
    // Test remove/add social link
    socialUser.removeFederatedIdentity("facebook1");
    Assert.assertEquals(2, socialUser.getFederatedIdentity().size());
    socialUser.addFederatedIdentity("facebook1", facebookIdentityRep);
    Assert.assertEquals(3, socialUser.getFederatedIdentity().size());
    // Test smtp config
    Map<String, String> smtpConfig = realm.getSmtpServer();
    Assert.assertTrue(smtpConfig.size() == 3);
    Assert.assertEquals("auto@keycloak.org", smtpConfig.get("from"));
    Assert.assertEquals("localhost", smtpConfig.get("host"));
    Assert.assertEquals("3025", smtpConfig.get("port"));
    // Test identity providers
    List<IdentityProviderRepresentation> identityProviders = realm.getIdentityProviders();
    Assert.assertEquals(3, identityProviders.size());
    IdentityProviderRepresentation google = null;
    for (IdentityProviderRepresentation idpRep : identityProviders) {
        if (idpRep.getAlias().equals("google1"))
            google = idpRep;
    }
    Assert.assertNotNull(google);
    Assert.assertEquals("google1", google.getAlias());
    Assert.assertEquals("google", google.getProviderId());
    Assert.assertTrue(google.isEnabled());
    Assert.assertEquals("googleId", google.getConfig().get("clientId"));
    Assert.assertEquals("googleSecret", google.getConfig().get("clientSecret"));
    // ////////////////
    // Test federation providers
    // on import should convert UserfederationProviderRepresentation to Component model
    List<UserFederationProviderRepresentation> fedProviders = realm.getUserFederationProviders();
    Assert.assertTrue(fedProviders == null || fedProviders.size() == 0);
    List<ComponentRepresentation> storageProviders = realmRsc.components().query(realm.getId(), UserStorageProvider.class.getName());
    Assert.assertTrue(storageProviders.size() == 2);
    ComponentRepresentation ldap1 = storageProviders.get(0);
    ComponentRepresentation ldap2 = storageProviders.get(1);
    if (!"MyLDAPProvider1".equals(ldap1.getName())) {
        ldap2 = ldap1;
        ldap1 = storageProviders.get(1);
    }
    Assert.assertEquals("MyLDAPProvider1", ldap1.getName());
    Assert.assertEquals("ldap", ldap1.getProviderId());
    Assert.assertEquals("1", ldap1.getConfig().getFirst("priority"));
    Assert.assertEquals("ldap://foo", ldap1.getConfig().getFirst(LDAPConstants.CONNECTION_URL));
    Assert.assertEquals("MyLDAPProvider2", ldap2.getName());
    Assert.assertEquals("ldap://bar", ldap2.getConfig().getFirst(LDAPConstants.CONNECTION_URL));
    // Test federation mappers
    List<ComponentRepresentation> fedMappers1 = realmRsc.components().query(ldap1.getId(), LDAPStorageMapper.class.getName());
    ComponentRepresentation fullNameMapper = fedMappers1.iterator().next();
    Assert.assertEquals("FullNameMapper", fullNameMapper.getName());
    Assert.assertEquals(FullNameLDAPStorageMapperFactory.PROVIDER_ID, fullNameMapper.getProviderId());
    Assert.assertEquals("cn", fullNameMapper.getConfig().getFirst(FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE));
    // ///////////////
    // Assert that federation link wasn't created during import
    Assert.assertNull(testingClient.testing().getUserByUsernameFromFedProviderFactory(realm.getRealm(), "wburke"));
    // Test builtin authentication flows
    AuthenticationFlowRepresentation clientFlow = testingClient.testing().getClientAuthFlow(realm.getRealm());
    Assert.assertEquals(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW, clientFlow.getAlias());
    Assert.assertNotNull(realmRsc.flows().getFlow(clientFlow.getId()));
    Assert.assertTrue(realmRsc.flows().getExecutions(clientFlow.getAlias()).size() > 0);
    AuthenticationFlowRepresentation resetFlow = testingClient.testing().getResetCredFlow(realm.getRealm());
    Assert.assertEquals(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW, resetFlow.getAlias());
    Assert.assertNotNull(realmRsc.flows().getFlow(resetFlow.getId()));
    Assert.assertTrue(realmRsc.flows().getExecutions(resetFlow.getAlias()).size() > 0);
    // Test protocol mappers. Default application doesn't have any builtin protocol mappers. OtherApp just gss credential
    List<ProtocolMapperRepresentation> applicationMappers = application.getProtocolMappers();
    // application.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, "username"));
    Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username"));
    Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "email"));
    Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "given name"));
    Assert.assertNull(findMapperByName(applicationMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME));
    Assert.assertEquals(1, otherApp.getProtocolMappers().size());
    List<ProtocolMapperRepresentation> otherAppMappers = otherApp.getProtocolMappers();
    Assert.assertNull(findMapperByName(otherAppMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "username"));
    ProtocolMapperRepresentation gssCredentialMapper = findMapperByName(otherAppMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME);
    assertGssProtocolMapper(gssCredentialMapper);
    // Test clientScopes
    List<ClientScopeRepresentation> clientScopes = realmRsc.clientScopes().findAll();
    ClientScopeRepresentation clientScope = clientScopes.stream().filter((ClientScopeRepresentation clientScope1) -> {
        return "foo_scope".equals(clientScope1.getName());
    }).findFirst().get();
    Assert.assertEquals("foo_scope", clientScope.getName());
    Assert.assertEquals("foo scope-desc", clientScope.getDescription());
    Assert.assertEquals(OIDCLoginProtocol.LOGIN_PROTOCOL, clientScope.getProtocol());
    Assert.assertEquals(1, clientScope.getProtocolMappers().size());
    List<ProtocolMapperRepresentation> clientScopeMappers = clientScope.getProtocolMappers();
    ProtocolMapperRepresentation scopeGssCredentialMapper = findMapperByName(clientScopeMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME);
    assertGssProtocolMapper(scopeGssCredentialMapper);
    // Test client scope - scopes
    Set<RoleRepresentation> allClientScopeScopes = allScopeMappings(realmRsc.clientScopes().get(clientScope.getId()));
    Assert.assertEquals(3, allClientScopeScopes.size());
    Assert.assertTrue(containsRole(allClientScopeScopes, findRealmRole(realmRsc, "admin")));
    Assert.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-user")));
    Assert.assertTrue(containsRole(allClientScopeScopes, findClientRole(realmRsc, application.getId(), "app-admin")));
    List<RoleRepresentation> clientScopeRealmScopes = realmScopeMappings(realmRsc.clientScopes().get(clientScope.getId()));
    Assert.assertTrue(containsRole(clientScopeRealmScopes, findRealmRole(realmRsc, "admin")));
    List<RoleRepresentation> clientScopeAppScopes = clientScopeMappings(realmRsc.clientScopes().get(clientScope.getId()));
    Assert.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-user")));
    Assert.assertTrue(containsRole(clientScopeAppScopes, findClientRole(realmRsc, application.getId(), "app-admin")));
    // Test client scopes assignment
    Assert.assertTrue(otherApp.getDefaultClientScopes().contains("foo_scope"));
    Assert.assertFalse(application.getDefaultClientScopes().contains("foo_scope"));
    // Test builtin client scopes
    testRealmDefaultClientScopes(realmRsc);
    // Test user consents
    UserResource adminRsc = realmRsc.users().get(admin.getId());
    List<Map<String, Object>> consents = adminRsc.getConsents();
    // .getConsents().size());
    Assert.assertEquals(2, consents.size());
    Map<String, Object> appAdminConsent = findConsentByClientId(consents, application.getClientId());
    Assert.assertNotNull(appAdminConsent);
    Assert.assertTrue(isClientScopeGranted(appAdminConsent, OAuth2Constants.OFFLINE_ACCESS, "roles", "profile", "email", "account", "web-origins"));
    // admin.getConsentByClient(otherApp.getId());
    Map<String, Object> otherAppAdminConsent = findConsentByClientId(consents, otherApp.getClientId());
    Assert.assertFalse(isClientScopeGranted(otherAppAdminConsent, OAuth2Constants.OFFLINE_ACCESS));
    Assert.assertTrue(application.isStandardFlowEnabled());
    Assert.assertTrue(application.isImplicitFlowEnabled());
    Assert.assertTrue(application.isDirectAccessGrantsEnabled());
    Assert.assertFalse(otherApp.isStandardFlowEnabled());
    Assert.assertFalse(otherApp.isImplicitFlowEnabled());
    Assert.assertFalse(otherApp.isDirectAccessGrantsEnabled());
    // Test service accounts
    Assert.assertFalse(application.isServiceAccountsEnabled());
    Assert.assertTrue(otherApp.isServiceAccountsEnabled());
    if (ProfileAssume.isFeatureEnabled(Profile.Feature.AUTHORIZATION)) {
        Assert.assertTrue(testAppAuthzApp.isServiceAccountsEnabled());
        // session.users().getUserByServiceAccountClient(application));
        Assert.assertNull(testingClient.testing().getUserByServiceAccountClient(realm.getRealm(), application.getClientId()));
        // session.users().getUserByServiceAccountClient(otherApp);
        UserRepresentation otherAppSA = testingClient.testing().getUserByServiceAccountClient(realm.getRealm(), otherApp.getClientId());
        Assert.assertNotNull(otherAppSA);
        Assert.assertEquals("service-account-otherapp", otherAppSA.getUsername());
        UserRepresentation testAppAuthzSA = testingClient.testing().getUserByServiceAccountClient(realm.getRealm(), testAppAuthzApp.getClientId());
        Assert.assertNotNull(testAppAuthzSA);
        Assert.assertEquals("service-account-test-app-authz", testAppAuthzSA.getUsername());
        // test service account maintains the roles in OtherApp
        allRoles = allRoles(realmRsc, otherAppSA);
        Assert.assertEquals(3, allRoles.size());
        Assert.assertTrue(containsRole(allRoles, findRealmRole(realmRsc, "user")));
        Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-user")));
        Assert.assertTrue(containsRole(allRoles, findClientRole(realmRsc, otherApp.getId(), "otherapp-admin")));
        assertAuthorizationSettingsOtherApp(realmRsc);
        assertAuthorizationSettingsTestAppAuthz(realmRsc);
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) AuthenticationFlowRepresentation(org.keycloak.representations.idm.AuthenticationFlowRepresentation) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) UserFederationProviderRepresentation(org.keycloak.representations.idm.UserFederationProviderRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) PasswordCredentialData(org.keycloak.models.credential.dto.PasswordCredentialData) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) UserResource(org.keycloak.admin.client.resource.UserResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) UserStorageProvider(org.keycloak.storage.UserStorageProvider) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Map(java.util.Map)

Example 78 with ProtocolMapperRepresentation

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

the class AccountRestServiceTest method testAudience.

@Test
public void testAudience() throws Exception {
    oauth.clientId("custom-audience");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    assertNull(tokenResponse.getErrorDescription());
    SimpleHttp.Response response = SimpleHttp.doGet(getAccountUrl(null), httpClient).auth(tokenResponse.getAccessToken()).header("Accept", "application/json").asResponse();
    assertEquals(401, response.getStatus());
    // update to correct audience
    org.keycloak.representations.idm.ClientRepresentation clientRep = testRealm().clients().findByClientId("custom-audience").get(0);
    ProtocolMapperRepresentation mapperRep = clientRep.getProtocolMappers().stream().filter(m -> m.getName().equals("aud")).findFirst().orElse(null);
    assertNotNull("Audience mapper not found", mapperRep);
    mapperRep.getConfig().put("included.custom.audience", "account");
    testRealm().clients().get(clientRep.getId()).getProtocolMappers().update(mapperRep.getId(), mapperRep);
    tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    assertNull(tokenResponse.getErrorDescription());
    response = SimpleHttp.doGet(getAccountUrl(null), httpClient).auth(tokenResponse.getAccessToken()).header("Accept", "application/json").asResponse();
    assertEquals(200, response.getStatus());
    // remove audience completely
    testRealm().clients().get(clientRep.getId()).getProtocolMappers().delete(mapperRep.getId());
    tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
    assertNull(tokenResponse.getErrorDescription());
    response = SimpleHttp.doGet(getAccountUrl(null), httpClient).auth(tokenResponse.getAccessToken()).header("Accept", "application/json").asResponse();
    assertEquals(401, response.getStatus());
// custom-audience client is used only in this test so no need to revert the changes
}
Also used : SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) Test(org.junit.Test) AbstractAuthenticationTest(org.keycloak.testsuite.admin.authentication.AbstractAuthenticationTest)

Example 79 with ProtocolMapperRepresentation

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

the class ClientRegistrationPoliciesTest method testProtocolMappersRemoveBuiltins.

@Test
// We would need to do domain name -> ip address to set trusted host
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testProtocolMappersRemoveBuiltins() throws Exception {
    setTrustedHost("localhost");
    // Change policy to allow hardcoded mapper
    ComponentRepresentation protocolMapperPolicyRep = findPolicyByProviderAndAuth(ProtocolMappersClientRegistrationPolicyFactory.PROVIDER_ID, getPolicyAnon());
    protocolMapperPolicyRep.getConfig().add(ProtocolMappersClientRegistrationPolicyFactory.ALLOWED_PROTOCOL_MAPPER_TYPES, HardcodedRole.PROVIDER_ID);
    realmResource().components().component(protocolMapperPolicyRep.getId()).update(protocolMapperPolicyRep);
    // Create client with hardcoded mapper
    ClientRepresentation clientRep = createRep("test-app");
    clientRep.setProtocolMappers(Collections.singletonList(createHardcodedMapperRep()));
    ClientRepresentation registeredClient = reg.create(clientRep);
    Assert.assertEquals(1, registeredClient.getProtocolMappers().size());
    ProtocolMapperRepresentation hardcodedMapper = registeredClient.getProtocolMappers().get(0);
    // Revert
    ApiUtil.findClientResourceByClientId(realmResource(), "test-app").remove();
    protocolMapperPolicyRep.getConfig().remove(ProtocolMappersClientRegistrationPolicyFactory.ALLOWED_PROTOCOL_MAPPER_TYPES, HardcodedRole.PROVIDER_ID);
    realmResource().components().component(protocolMapperPolicyRep.getId()).update(protocolMapperPolicyRep);
}
Also used : ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 80 with ProtocolMapperRepresentation

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

the class RoleMapperTest method createSamlProtocolMapper.

public static ProtocolMapperRepresentation createSamlProtocolMapper(String protocolMapperProviderId, String... configKeyValue) {
    ProtocolMapperRepresentation res = new ProtocolMapperRepresentation();
    res.setProtocol(SamlProtocol.LOGIN_PROTOCOL);
    res.setName(protocolMapperProviderId + "-" + RoleMapperTest.COUNTER++);
    res.setProtocolMapper(protocolMapperProviderId);
    Map<String, String> config = new HashMap<>();
    for (int i = 0; i < configKeyValue.length - 1; i += 2) {
        String key = configKeyValue[i];
        String value = configKeyValue[i + 1];
        config.put(key, value);
    }
    res.setConfig(config);
    return res;
}
Also used : HashMap(java.util.HashMap) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation)

Aggregations

ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)107 Test (org.junit.Test)68 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)30 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)27 Map (java.util.Map)23 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)20 ClientResource (org.keycloak.admin.client.resource.ClientResource)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)17 RealmResource (org.keycloak.admin.client.resource.RealmResource)14 List (java.util.List)13 ProtocolMappersResource (org.keycloak.admin.client.resource.ProtocolMappersResource)12 IDToken (org.keycloak.representations.IDToken)12 Matchers.isEmptyOrNullString (org.hamcrest.Matchers.isEmptyOrNullString)11 ClientScopeRepresentation (org.keycloak.representations.idm.ClientScopeRepresentation)11 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)10 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)8 ArrayList (java.util.ArrayList)7 LinkedList (java.util.LinkedList)7 AccessToken (org.keycloak.representations.AccessToken)7