Java Code Examples for org.keycloak.models.utils.KeycloakModelUtils#generateId()

The following examples show how to use org.keycloak.models.utils.KeycloakModelUtils#generateId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public RequiredActionProviderModel addRequiredActionProvider(RequiredActionProviderModel model) {
    RequiredActionProviderEntity auth = new RequiredActionProviderEntity();
    String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId();
    auth.setId(id);
    auth.setAlias(model.getAlias());
    auth.setName(model.getName());
    auth.setRealm(realm);
    auth.setProviderId(model.getProviderId());
    auth.setConfig(model.getConfig());
    auth.setEnabled(model.isEnabled());
    auth.setDefaultAction(model.isDefaultAction());
    auth.setPriority(model.getPriority());
    realm.getRequiredActionProviders().add(auth);
    em.persist(auth);
    em.flush();
    model.setId(auth.getId());
    return model;
}
 
Example 2
Source File: AdminEventAuthDetailsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmBuilder realm = RealmBuilder.create().name("test").testEventListener();
    client1Uuid = KeycloakModelUtils.generateId();
    realm.client(ClientBuilder.create().id(client1Uuid).clientId("client1").publicClient().directAccessGrants());

    admin1Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin1Id).username("admin1").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    admin2Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin2Id).username("admin2").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    appUserId =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(appUserId).username("app-user").password("password"));

    testRealms.add(realm.build());
}
 
Example 3
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationExecutionModel addAuthenticatorExecution(AuthenticationExecutionModel model) {
    AuthenticationExecutionEntity entity = new AuthenticationExecutionEntity();
    String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId();
    entity.setId(id);
    entity.setAuthenticator(model.getAuthenticator());
    entity.setPriority(model.getPriority());
    entity.setFlowId(model.getFlowId());
    entity.setRequirement(model.getRequirement());
    entity.setAuthenticatorConfig(model.getAuthenticatorConfig());
    AuthenticationFlowEntity flow = em.find(AuthenticationFlowEntity.class, model.getParentFlow());
    entity.setParentFlow(flow);
    flow.getExecutions().add(entity);
    entity.setRealm(realm);
    entity.setAutheticatorFlow(model.isAuthenticatorFlow());
    em.persist(entity);
    model.setId(entity.getId());
    return model;

}
 
Example 4
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) {
    if (getIdentityProviderMapperByName(model.getIdentityProviderAlias(), model.getName()) != null) {
        throw new RuntimeException("identity provider mapper name must be unique per identity provider");
    }
    String id = KeycloakModelUtils.generateId();
    IdentityProviderMapperEntity entity = new IdentityProviderMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setIdentityProviderAlias(model.getIdentityProviderAlias());
    entity.setIdentityProviderMapper(model.getIdentityProviderMapper());
    entity.setRealm(this.realm);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.realm.getIdentityProviderMappers().add(entity);
    return entityToModel(entity);
}
 
Example 5
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void addAdminRole(String roleName, String realmId, String applicationId, String realmAdminAppRoleId) {
    String roleTableName = database.correctObjectName("KEYCLOAK_ROLE", Table.class);
    String compositeRoleTableName = database.correctObjectName("COMPOSITE_ROLE", Table.class);
    String newRoleId = KeycloakModelUtils.generateId();

    InsertStatement insertRole = new InsertStatement(null, null, roleTableName)
            .addColumnValue("ID", newRoleId)
            .addColumnValue("APP_REALM_CONSTRAINT", applicationId)
            .addColumnValue("APPLICATION_ROLE", true)
            .addColumnValue("NAME", roleName)
            .addColumnValue("REALM_ID", realmId)
            .addColumnValue("APPLICATION", applicationId);

    // Add newly created role to the composite roles of 'realm-admin' role
    InsertStatement insertCompRole = new InsertStatement(null, null, compositeRoleTableName)
            .addColumnValue("COMPOSITE", realmAdminAppRoleId)
            .addColumnValue("CHILD_ROLE", newRoleId);

    statements.add(insertRole);
    statements.add(insertCompRole);
}
 
Example 6
Source File: ClientScopeAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClientScope(this.entity);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
 
Example 7
Source File: SHA256PairwiseSubMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ProtocolMapperRepresentation createPairwiseMapper(String sectorIdentifierUri, String salt) {
    Map<String, String> config;
    ProtocolMapperRepresentation pairwise = new ProtocolMapperRepresentation();
    pairwise.setName("pairwise subject identifier");
    pairwise.setProtocolMapper(new SHA256PairwiseSubMapper().getId());
    pairwise.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    config = new HashMap<>();
    config.put(PairwiseSubMapperHelper.SECTOR_IDENTIFIER_URI, sectorIdentifierUri);
    if (salt == null) {
        salt = KeycloakModelUtils.generateId();
    }
    config.put(PairwiseSubMapperHelper.PAIRWISE_SUB_ALGORITHM_SALT, salt);
    pairwise.setConfig(config);
    return pairwise;
}
 
Example 8
Source File: RealmAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticatorConfigModel addAuthenticatorConfig(AuthenticatorConfigModel model) {
    AuthenticatorConfigEntity auth = new AuthenticatorConfigEntity();
    String id = (model.getId() == null) ? KeycloakModelUtils.generateId(): model.getId();
    auth.setId(id);
    auth.setAlias(model.getAlias());
    auth.setRealm(realm);
    auth.setConfig(model.getConfig());
    realm.getAuthenticatorConfigs().add(auth);
    em.persist(auth);
    model.setId(auth.getId());
    return model;
}
 
Example 9
Source File: AbstractGeneratedSecretKeyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void generateSecret(ComponentModel model, int size) {
    try {
        byte[] secret = KeycloakModelUtils.generateSecret(size);
        model.put(Attributes.SECRET_KEY, Base64Url.encode(secret));

        String kid = KeycloakModelUtils.generateId();
        model.put(Attributes.KID_KEY, kid);
    } catch (Throwable t) {
        throw new ComponentValidationException("Failed to generate secret", t);
    }
}
 
Example 10
Source File: ClientRegistrationTokenUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String updateRegistrationAccessToken(KeycloakSession session, RealmModel realm, ClientModel client, RegistrationAuth registrationAuth) {
    String id = KeycloakModelUtils.generateId();
    client.setRegistrationToken(id);

    RegistrationAccessToken regToken = new RegistrationAccessToken();
    regToken.setRegistrationAuth(registrationAuth.toString().toLowerCase());

    return setupToken(regToken, session, realm, id, TYPE_REGISTRATION_ACCESS_TOKEN, 0);
}
 
Example 11
Source File: ExampleServiceImpl.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public CompanyRepresentation addCompany(CompanyRepresentation company) {
    Company entity = new Company();
    String id = company.getId()==null ?  KeycloakModelUtils.generateId() : company.getId();
    entity.setId(id);
    entity.setName(company.getName());
    entity.setRealmId(getRealm().getId());
    getEntityManager().persist(entity);

    company.setId(id);
    return company;
}
 
Example 12
Source File: OfflineTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {

    RealmRepresentation realmRepresentation = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);

    RealmBuilder realm = RealmBuilder.edit(realmRepresentation)
            .accessTokenLifespan(10)
            .ssoSessionIdleTimeout(30)
            .testEventListener();

    offlineClientAppUri = APP_ROOT + "/offline-client";

    ClientRepresentation app = ClientBuilder.create().clientId("offline-client")
            .id(KeycloakModelUtils.generateId())
            .adminUrl(offlineClientAppUri)
            .redirectUris(offlineClientAppUri)
            .directAccessGrants()
            .serviceAccountsEnabled(true)
            .secret("secret1").build();

    realm.client(app);

    serviceAccountUserId = KeycloakModelUtils.generateId();
    UserRepresentation serviceAccountUser = UserBuilder.create()
            .id(serviceAccountUserId)
            .addRoles("user", "offline_access")
            .role("test-app", "customer-user")
            .username(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + app.getClientId())
            .serviceAccountId(app.getClientId()).build();

    realm.user(serviceAccountUser);

    testRealms.add(realm.build());

}
 
Example 13
Source File: ImpersonationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmBuilder realm = RealmBuilder.create().name("test").testEventListener();

    realm.client(ClientBuilder.create().clientId("myclient").publicClient().directAccessGrants());

    impersonatedUserId = KeycloakModelUtils.generateId();

    realm.user(UserBuilder.create().id(impersonatedUserId).username("test-user@localhost"));
    realm.user(UserBuilder.create().username("realm-admin").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));
    realm.user(UserBuilder.create().username("impersonator").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, ImpersonationConstants.IMPERSONATION_ROLE).role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.VIEW_USERS));
    realm.user(UserBuilder.create().username("bad-impersonator").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.MANAGE_USERS));

    testRealms.add(realm.build());
}
 
Example 14
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public RealmModel createRealm(String id, String name) {
    if (id == null) id = KeycloakModelUtils.generateId();
    ReservedCharValidator.validate(name);
    RealmModel realm = model.createRealm(id, name);
    realm.setName(name);

    // setup defaults
    setupRealmDefaults(realm);

    setupMasterAdminManagement(realm);
    setupRealmAdminManagement(realm);
    setupAccountManagement(realm);
    setupBrokerService(realm);
    setupAdminConsole(realm);
    setupAdminConsoleLocaleMapper(realm);
    setupAdminCli(realm);
    setupImpersonationService(realm);
    setupAuthenticationFlows(realm);
    setupRequiredActions(realm);
    setupOfflineTokens(realm, null);
    createDefaultClientScopes(realm);
    setupAuthorizationServices(realm);
    setupClientRegistrations(realm);

    fireRealmPostCreate(realm);

    return realm;
}
 
Example 15
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void convertSocialToIdFedRealms() throws SQLException, DatabaseException {
    String identityProviderTableName = database.correctObjectName("IDENTITY_PROVIDER", Table.class);
    String idpConfigTableName = database.correctObjectName("IDENTITY_PROVIDER_CONFIG", Table.class);

    String realmSocialConfigTable = getTableName("REALM_SOCIAL_CONFIG");
    String realmTableName = getTableName("REALM");
    PreparedStatement statement = jdbcConnection.prepareStatement("select RSC.NAME, VALUE, REALM_ID, UPDATE_PROFILE_ON_SOC_LOGIN from " + realmSocialConfigTable + " RSC," + realmTableName +
            " REALM where RSC.REALM_ID = REALM.ID ORDER BY RSC.REALM_ID, RSC.NAME");
    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            boolean providerInProgress = false;
            String socialProviderId = null;
            String clientId = null;
            String clientSecret;
            String realmId = null;
            boolean updateProfileOnSocialLogin = false;
            boolean first = true;

            while (resultSet.next()) {
                if (first) {
                    confirmationMessage.append("Migrating social to identity providers: ");
                    first = false;
                }

                if (!providerInProgress) {
                    String key = resultSet.getString("NAME");
                    int keyIndex = key.indexOf(".key");
                    if (keyIndex == -1) {
                        throw new IllegalStateException("Can't parse the provider from column: " + key);
                    }

                    socialProviderId = key.substring(0, keyIndex);
                    clientId = resultSet.getString("VALUE");
                    realmId = resultSet.getString("REALM_ID");
                    updateProfileOnSocialLogin = resultSet.getBoolean("UPDATE_PROFILE_ON_SOC_LOGIN");
                    providerInProgress = true;
                } else {
                    clientSecret = resultSet.getString("VALUE");

                    String internalId = KeycloakModelUtils.generateId();
                    InsertStatement idpInsert = new InsertStatement(null, null, identityProviderTableName)
                            .addColumnValue("INTERNAL_ID", internalId)
                            .addColumnValue("ENABLED", true)
                            .addColumnValue("PROVIDER_ALIAS", socialProviderId)
                            .addColumnValue("PROVIDER_ID", socialProviderId)
                            .addColumnValue("UPDATE_PROFILE_FIRST_LOGIN", updateProfileOnSocialLogin)
                            .addColumnValue("STORE_TOKEN", false)
                            .addColumnValue("AUTHENTICATE_BY_DEFAULT", false)
                            .addColumnValue("REALM_ID", realmId);
                    InsertStatement clientIdInsert = new InsertStatement(null, null, idpConfigTableName)
                            .addColumnValue("IDENTITY_PROVIDER_ID", internalId)
                            .addColumnValue("NAME", "clientId")
                            .addColumnValue("VALUE", clientId);
                    InsertStatement clientSecretInsert = new InsertStatement(null, null, idpConfigTableName)
                            .addColumnValue("IDENTITY_PROVIDER_ID", internalId)
                            .addColumnValue("NAME", "clientSecret")
                            .addColumnValue("VALUE", clientSecret);

                    statements.add(idpInsert);
                    statements.add(clientIdInsert);
                    statements.add(clientSecretInsert);
                    confirmationMessage.append(socialProviderId + " in realm " + realmId + ", ");

                    providerInProgress = false;
                }
            }

            // It means that some provider where processed
            if (!first) {
                confirmationMessage.append(". ");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example 16
Source File: RealmManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * if "skipUserDependent" is true, then import of any models, which needs users already imported in DB, will be skipped. For example authorization
 */
public RealmModel importRealm(RealmRepresentation rep, boolean skipUserDependent) {
    String id = rep.getId();
    if (id == null) {
        id = KeycloakModelUtils.generateId();
    }
    RealmModel realm = model.createRealm(id, rep.getRealm());
    ReservedCharValidator.validate(rep.getRealm());
    realm.setName(rep.getRealm());

    // setup defaults

    setupRealmDefaults(realm);

    boolean postponeMasterClientSetup = postponeMasterClientSetup(rep);
    if (!postponeMasterClientSetup) {
        setupMasterAdminManagement(realm);
    }

    if (!hasRealmAdminManagementClient(rep)) setupRealmAdminManagement(realm);
    if (!hasAccountManagementClient(rep)) setupAccountManagement(realm);

    boolean postponeImpersonationSetup = false;
    if (hasRealmAdminManagementClient(rep)) {
        postponeImpersonationSetup = true;
    } else {
        setupImpersonationService(realm);
    }


    if (!hasBrokerClient(rep)) setupBrokerService(realm);
    if (!hasAdminConsoleClient(rep)) setupAdminConsole(realm);

    boolean postponeAdminCliSetup = false;
    if (!hasAdminCliClient(rep)) {
        if (hasRealmAdminManagementClient(rep)) {
            postponeAdminCliSetup = true;
        } else {
            setupAdminCli(realm);
        }
    }

    if (!hasRealmRole(rep, Constants.OFFLINE_ACCESS_ROLE) || !hasClientScope(rep, Constants.OFFLINE_ACCESS_ROLE)) {
        setupOfflineTokens(realm, rep);
    }

    if (rep.getClientScopes() == null) {
        createDefaultClientScopes(realm);
    }

    RepresentationToModel.importRealm(session, rep, realm, skipUserDependent);
    List<ClientRepresentation> clients = rep.getClients();

    setupClientServiceAccountsAndAuthorizationOnImport(rep, skipUserDependent);

    setupAdminConsoleLocaleMapper(realm);

    if (postponeMasterClientSetup) {
        setupMasterAdminManagement(realm);
    }

    if (rep.getRoles() != null || hasRealmAdminManagementClient(rep)) {
    	// Assert all admin roles are available once import took place. This is needed due to import from previous version where JSON file may not contain all admin roles
    	checkMasterAdminManagementRoles(realm);
    	checkRealmAdminManagementRoles(realm);
    }

    // Could happen when migrating from older version and I have exported JSON file, which contains "realm-management" client but not "impersonation" client
    // I need to postpone impersonation because it needs "realm-management" client and its roles set
    if (postponeImpersonationSetup) {
        setupImpersonationService(realm);
        String realmAdminClientId = getRealmAdminClientId(realm);
     }

    if (postponeAdminCliSetup) {
        setupAdminCli(realm);
    }

    setupAuthenticationFlows(realm);
    setupRequiredActions(realm);

    // Refresh periodic sync tasks for configured storageProviders
    List<UserStorageProviderModel> storageProviders = realm.getUserStorageProviders();
    UserStorageSyncManager storageSync = new UserStorageSyncManager();
    for (UserStorageProviderModel provider : storageProviders) {
        storageSync.notifyToRefreshPeriodicSync(session, realm, provider, false);
    }

    setupAuthorizationServices(realm);
    setupClientRegistrations(realm);

    if (rep.getKeycloakVersion() != null) {
        MigrationModelManager.migrateImport(session, realm, rep, skipUserDependent);
    }

    fireRealmPostCreate(realm);

    return realm;
}
 
Example 17
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void addDefaultProtocolMappers() throws SQLException, DatabaseException {
    String protocolMapperTableName = database.correctObjectName("PROTOCOL_MAPPER", Table.class);
    String protocolMapperCfgTableName = database.correctObjectName("PROTOCOL_MAPPER_CONFIG", Table.class);

    PreparedStatement statement = jdbcConnection.prepareStatement("select ID, NAME, ALLOWED_CLAIMS_MASK from " + getTableName("CLIENT"));

    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            boolean first = true;
            while (resultSet.next()) {
                if (first) {
                    confirmationMessage.append("Migrating claimsMask to protocol mappers for clients: ");
                    first = false;
                }

                Object acmObj = resultSet.getObject("ALLOWED_CLAIMS_MASK");
                long mask = (acmObj != null) ? ((Number) acmObj).longValue() : ClaimMask.ALL;

                MigrationProvider migrationProvider = this.kcSession.getProvider(MigrationProvider.class);
                List<ProtocolMapperRepresentation> protocolMappers = migrationProvider.getMappersForClaimMask(mask);

                for (ProtocolMapperRepresentation protocolMapper : protocolMappers) {
                    String mapperId = KeycloakModelUtils.generateId();

                    InsertStatement insert = new InsertStatement(null, null, protocolMapperTableName)
                            .addColumnValue("ID", mapperId)
                            .addColumnValue("PROTOCOL", protocolMapper.getProtocol())
                            .addColumnValue("NAME", protocolMapper.getName())
                            .addColumnValue("CONSENT_REQUIRED", false)
                            .addColumnValue("PROTOCOL_MAPPER_NAME", protocolMapper.getProtocolMapper())
                            .addColumnValue("CLIENT_ID", resultSet.getString("ID"));
                    statements.add(insert);

                    for (Map.Entry<String, String> cfgEntry : protocolMapper.getConfig().entrySet()) {
                        InsertStatement cfgInsert = new InsertStatement(null, null, protocolMapperCfgTableName)
                                .addColumnValue("PROTOCOL_MAPPER_ID", mapperId)
                                .addColumnValue("NAME", cfgEntry.getKey())
                                .addColumnValue("VALUE", cfgEntry.getValue());
                        statements.add(cfgInsert);
                    }

                }

                confirmationMessage.append(resultSet.getString("NAME") + ", ");
            }

            // It means that some provider where processed
            if (!first) {
                confirmationMessage.append(". ");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example 18
Source File: ServiceAccountTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {

    RealmBuilder realm = RealmBuilder.create().name("test")
            .privateKey("MIICXAIBAAKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQABAoGAfmO8gVhyBxdqlxmIuglbz8bcjQbhXJLR2EoS8ngTXmN1bo2L90M0mUKSdc7qF10LgETBzqL8jYlQIbt+e6TH8fcEpKCjUlyq0Mf/vVbfZSNaVycY13nTzo27iPyWQHK5NLuJzn1xvxxrUeXI6A2WFpGEBLbHjwpx5WQG9A+2scECQQDvdn9NE75HPTVPxBqsEd2z10TKkl9CZxu10Qby3iQQmWLEJ9LNmy3acvKrE3gMiYNWb6xHPKiIqOR1as7L24aTAkEAtyvQOlCvr5kAjVqrEKXalj0Tzewjweuxc0pskvArTI2Oo070h65GpoIKLc9jf+UA69cRtquwP93aZKtW06U8dQJAF2Y44ks/mK5+eyDqik3koCI08qaC8HYq2wVl7G2QkJ6sbAaILtcvD92ToOvyGyeE0flvmDZxMYlvaZnaQ0lcSQJBAKZU6umJi3/xeEbkJqMfeLclD27XGEFoPeNrmdx0q10Azp4NfJAY+Z8KRyQCR2BEG+oNitBOZ+YXF9KCpH3cdmECQHEigJhYg+ykOvr1aiZUMFT72HU0jnmQe2FVekuG+LJUt2Tm7GtMjTFoGpf0JwrVuZN39fOYAlo+nTixgeW7X8Y=")
            .publicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB")
            .testEventListener();

    ClientRepresentation enabledApp = ClientBuilder.create()
            .id(KeycloakModelUtils.generateId())
            .clientId("service-account-cl")
            .secret("secret1")
            .serviceAccountsEnabled(true)
            .build();

    realm.client(enabledApp);

    ClientRepresentation disabledApp = ClientBuilder.create()
            .id(KeycloakModelUtils.generateId())
            .clientId("service-account-disabled")
            .secret("secret1")
            .build();

    realm.client(disabledApp);

    UserBuilder defaultUser = UserBuilder.create()
            .id(KeycloakModelUtils.generateId())
            .username("test-user@localhost");
    realm.user(defaultUser);

    userId = KeycloakModelUtils.generateId();
    userName = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + enabledApp.getClientId();

    UserBuilder serviceAccountUser = UserBuilder.create()
            .id(userId)
            .username(userName)
            .serviceAccountId(enabledApp.getClientId());
    realm.user(serviceAccountUser);

    testRealms.add(realm.build());
}
 
Example 19
Source File: MultipleTabsLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testEmptyBaseUrl() throws Exception {
    String clientUuid = KeycloakModelUtils.generateId();
    ClientRepresentation emptyBaseclient = ClientBuilder.create()
            .clientId("empty-baseurl-client")
            .id(clientUuid)
            .enabled(true)
            .baseUrl("")
            .addRedirectUri("*")
            .secret("password")
            .build();
    testRealm().clients().create(emptyBaseclient);
    getCleanup().addClientUuid(clientUuid);

    oauth.clientId("empty-baseurl-client");
    oauth.openLoginForm();
    loginPage.assertCurrent();

    loginPage.login("login-test", "password");
    updatePasswordPage.assertCurrent();

    String tab1Url = driver.getCurrentUrl();

    // Simulate login in different browser tab tab2. I will be on loginPage again.
    oauth.openLoginForm();
    loginPage.assertCurrent();

    // Login in tab2
    loginPage.login("login-test", "password");
    updatePasswordPage.assertCurrent();

    updatePasswordPage.changePassword("password", "password");
    updateProfilePage.update("John", "Doe3", "[email protected]");
    appPage.assertCurrent();

    // Try to go back to tab 1. We should have ALREADY_LOGGED_IN info page
    driver.navigate().to(tab1Url);
    infoPage.assertCurrent();
    Assert.assertEquals("You are already logged in.", infoPage.getInfo());

    try {
        infoPage.clickBackToApplicationLink();
        fail();
    }
    catch (NoSuchElementException ex) {}
}
 
Example 20
Source File: SHA256PairwiseSubMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static String generateSalt() {
    return KeycloakModelUtils.generateId();
}