org.keycloak.models.KeycloakSession Java Examples

The following examples show how to use org.keycloak.models.KeycloakSession. 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: InfinispanClusterProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (workCache == null) {
        synchronized (this) {
            if (workCache == null) {
                InfinispanConnectionProvider ispnConnections = session.getProvider(InfinispanConnectionProvider.class);
                workCache = ispnConnections.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);

                workCache.getCacheManager().addListener(new ViewChangeListener());

                // See if we have RemoteStore (external JDG) configured for cross-Data-Center scenario
                Set<RemoteStore> remoteStores = InfinispanUtil.getRemoteStores(workCache);
                crossDCAwareCacheFactory = CrossDCAwareCacheFactory.getFactory(workCache, remoteStores);

                clusterStartupTime = initClusterStartupTime(session);

                TopologyInfo topologyInfo = InfinispanUtil.getTopologyInfo(session);
                String myAddress = topologyInfo.getMyNodeName();
                String mySite = topologyInfo.getMySiteName();

                notificationsManager = InfinispanNotificationsManager.create(session, workCache, myAddress, mySite, remoteStores);
            }
        }
    }
}
 
Example #2
Source File: TotpBean.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) {
    this.uriBuilder = uriBuilder;
    this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE);
    if (enabled) {
        List<CredentialModel> otpCredentials = session.userCredentialManager().getStoredCredentialsByType(realm, user, OTPCredentialModel.TYPE);

        if (otpCredentials.isEmpty()) {
            // Credential is configured on userStorage side. Create the "fake" credential similar like we do for the new account console
            CredentialRepresentation credential = createUserStorageCredentialRepresentation(OTPCredentialModel.TYPE);
            this.otpCredentials = Collections.singletonList(RepresentationToModel.toModel(credential));
        } else {
            this.otpCredentials = otpCredentials;
        }
    } else {
        this.otpCredentials = Collections.EMPTY_LIST;
    }

    this.realm = realm;
    this.totpSecret = HmacOTP.generateSecret(20);
    this.totpSecretEncoded = TotpUtils.encode(totpSecret);
    this.totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user);
}
 
Example #3
Source File: MigrateTo3_2_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm) {
    PasswordPolicy.Builder builder = realm.getPasswordPolicy().toBuilder();
    if (!builder.contains(PasswordPolicy.HASH_ALGORITHM_ID) && "20000".equals(builder.get(PasswordPolicy.HASH_ITERATIONS_ID))) {
        realm.setPasswordPolicy(builder.remove(PasswordPolicy.HASH_ITERATIONS_ID).build(session));
    }

    if (realm.getDockerAuthenticationFlow() == null) {
        DefaultAuthenticationFlows.dockerAuthenticationFlow(realm);
    }

    ClientModel realmAccess = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    if (realmAccess != null) {
        addRoles(realmAccess);
    }
    ClientModel masterAdminClient = realm.getMasterAdminClient();
    if (masterAdminClient != null) {
        addRoles(masterAdminClient);

    }
}
 
Example #4
Source File: AbstractJsonUserAttributeMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
	String attribute = getAttribute(mapperModel);
	if (attribute == null) {
		return;
	}

	Object value = getJsonValue(mapperModel, context);
	if (value == null) {
		user.removeAttribute(attribute);
	} else if (value instanceof List) {
		user.setAttribute(attribute, (List<String>) value);
	} else {
		user.setSingleAttribute(attribute, value.toString());
	}
}
 
Example #5
Source File: SingleFileExportProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    logger.infof("Exporting model into file %s", this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            List<RealmModel> realms = session.realms().getRealms();
            List<RealmRepresentation> reps = new ArrayList<>();
            for (RealmModel realm : realms) {
                reps.add(ExportUtils.exportRealm(session, realm, true, true));
            }

            writeToFile(reps);
        }

    });

}
 
Example #6
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void testCheckUserGroups(KeycloakSession session) {
    session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
    JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();

    policyRepresentation.setName("testCheckUserGroups");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var groups = realm.getUserGroups('jdoe');");
    builder.append("if (groups.size() == 2 && groups.contains('/Group A/Group B') && groups.contains('/Group A/Group D')) { $evaluation.grant(); }");

    policyRepresentation.setCode(builder.toString());

    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());

    DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);

    provider.evaluate(evaluation);

    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
 
Example #7
Source File: ComponentUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void notifyCreated(KeycloakSession session, RealmModel realm, ComponentModel model) {
    ComponentFactory factory = getComponentFactory(session, model);
    factory.onCreate(session, realm, model);
    if (factory instanceof UserStorageProviderFactory) {
        ((OnCreateComponent)session.userStorageManager()).onCreate(session, realm, model);
    }
}
 
Example #8
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response nextActionAfterAuthentication(KeycloakSession session, AuthenticationSessionModel authSession,
                                              ClientConnection clientConnection,
                                              HttpRequest request, UriInfo uriInfo, EventBuilder event) {
    Response requiredAction = actionRequired(session, authSession, clientConnection, request, uriInfo, event);
    if (requiredAction != null) return requiredAction;
    return finishedRequiredActions(session, authSession, null, clientConnection, request, uriInfo, event);

}
 
Example #9
Source File: Authenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if all required actions are configured in the realm and are enabled
 * @return
 */
default boolean areRequiredActionsEnabled(KeycloakSession session, RealmModel realm) {
    for (RequiredActionFactory raf : getRequiredActions(session)) {
        RequiredActionProviderModel rafpm = realm.getRequiredActionProviderByAlias(raf.getId());
        if (rafpm == null) {
            return false;
        }
        if (!rafpm.isEnabled()) {
            return false;
        }
    }
    return true;
}
 
Example #10
Source File: SamlProtocol.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AttributeStatementType populateAttributeStatements(List<ProtocolMapperProcessor<SAMLAttributeStatementMapper>> attributeStatementMappers, KeycloakSession session, UserSessionModel userSession,
                                                          AuthenticatedClientSessionModel clientSession) {
    AttributeStatementType attributeStatement = new AttributeStatementType();
    for (ProtocolMapperProcessor<SAMLAttributeStatementMapper> processor : attributeStatementMappers) {
        processor.mapper.transformAttributeStatement(attributeStatement, processor.model, session, userSession, clientSession);
    }

    return attributeStatement;
}
 
Example #11
Source File: RemoteOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Object fetchRemoteClaims(ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession) {

        try {
            String remoteUrl = mappingModel.getConfig().getOrDefault(REMOTE_URL_PROPERTY, "http://localhost:7777/claims");
            UserModel user = userSession.getUser();
            String url = remoteUrl + "?userId=" + user.getId() + "&username=" + URLEncoder.encode(user.getUsername(), "UTF-8");
            JsonNode jsonNode = SimpleHttp.doGet(url, keycloakSession).asJson();
            return jsonNode;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example #12
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void createFederatedIdentities(UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user) {
    if (userRep.getFederatedIdentities() != null) {
        for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
            FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
            session.users().addFederatedIdentity(realm, user, mappingModel);
        }
    }
}
 
Example #13
Source File: LDAPMSADFullNameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void assertUser(KeycloakSession session, LDAPTestContext ctx, UserModel user, String expectedUsername, String expectedFirstName, String expectedLastName, boolean expectedEnabled, String expectedDn) {
    Assert.assertNotNull(user);
    Assert.assertNotNull(user.getFederationLink());
    Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId());
    Assert.assertEquals(expectedUsername, user.getUsername());
    Assert.assertEquals(expectedFirstName, user.getFirstName());
    Assert.assertEquals(expectedLastName, user.getLastName());
    Assert.assertEquals(expectedEnabled, user.isEnabled());
    assertDnStartsWith(session, ctx, user, expectedDn);
}
 
Example #14
Source File: SingleFileImportProviderFactory.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ImportProvider create(KeycloakSession session) {
    String fileName = ExportImportConfig.getFile();
    if (fileName == null) {
        throw new IllegalArgumentException("Property " + ExportImportConfig.FILE + " needs to be provided!");
    }
    return new SingleFileImportProvider(new File(fileName));
}
 
Example #15
Source File: InfinispanKeyGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <K> K generateKey(KeycloakSession session, Cache<K, ?> cache, KeyGenerator<K> keyGenerator) {
    String cacheName = cache.getName();

    // "wantsLocalKey" is true if route is not attached to the sticky session cookie. Without attached route, We want the key, which will be "owned" by this node.
    // This is needed due the fact that external loadbalancer will attach route corresponding to our node, which will be the owner of the particular key, hence we
    // will be able to lookup key locally.
    boolean wantsLocalKey = !session.getProvider(StickySessionEncoderProvider.class).shouldAttachRoute();

    if (wantsLocalKey && cache.getCacheConfiguration().clustering().cacheMode().isClustered()) {
        KeyAffinityService<K> keyAffinityService = keyAffinityServices.get(cacheName);
        if (keyAffinityService == null) {
            keyAffinityService = createKeyAffinityService(cache, keyGenerator);
            keyAffinityServices.put(cacheName, keyAffinityService);

            log.debugf("Registered key affinity service for cache '%s'", cacheName);
        }

        return keyAffinityService.getKeyForAddress(cache.getCacheManager().getAddress());
    } else {
        return keyGenerator.getKey();
    }

}
 
Example #16
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param session
 * @param realm
 * @param userSession
 * @param uriInfo
 * @param connection
 * @param headers
 * @param logoutBroker
 * @param offlineSession
 */
public static void backchannelLogout(KeycloakSession session, RealmModel realm,
                                     UserSessionModel userSession, UriInfo uriInfo,
                                     ClientConnection connection, HttpHeaders headers,
                                     boolean logoutBroker,
                                     boolean offlineSession) {
    if (userSession == null) return;
    UserModel user = userSession.getUser();
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    logger.debugv("Logging out: {0} ({1}) offline: {2}", user.getUsername(), userSession.getId(), userSession.isOffline());
    expireUserSessionCookie(session, userSession, realm, uriInfo, headers, connection);

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, false);

    try {
        backchannelLogoutAll(session, realm, userSession, logoutAuthSession, uriInfo, headers, logoutBroker);
        checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    } finally {
        RootAuthenticationSessionModel rootAuthSession = logoutAuthSession.getParentSession();
        rootAuthSession.removeAuthenticationSessionByTabId(logoutAuthSession.getTabId());
    }

    userSession.setState(UserSessionModel.State.LOGGED_OUT);

    if (offlineSession) {
        new UserSessionManager(session).revokeOfflineUserSession(userSession);

        // Check if "online" session still exists and remove it too
        UserSessionModel onlineUserSession = session.sessions().getUserSession(realm, userSession.getId());
        if (onlineUserSession != null) {
            session.sessions().removeUserSession(realm, onlineUserSession);
        }
    } else {
        session.sessions().removeUserSession(realm, userSession);
    }
}
 
Example #17
Source File: UserStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> getEnabledStorageProviders(KeycloakSession session, RealmModel realm, Class<T> type) {
    List<T> list = new LinkedList<>();
    for (UserStorageProviderModel model : getStorageProviders(realm)) {
        if (!model.isEnabled()) continue;
        UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, model.getProviderId());
        if (factory == null) {
            logger.warnv("Configured UserStorageProvider {0} of provider id {1} does not exist in realm {2}", model.getName(), model.getProviderId(), realm.getName());
            continue;
        }
        if (Types.supports(type, factory, UserStorageProviderFactory.class)) {
            list.add(type.cast(getStorageProviderInstance(session, model, factory)));
        }


    }
    return list;
}
 
Example #18
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformAccessToken(KeycloakSession session, AccessToken token,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    for (Map.Entry<ProtocolMapperModel, ProtocolMapper> entry : ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx)) {
        ProtocolMapperModel mapping = entry.getKey();
        ProtocolMapper mapper = entry.getValue();
        if (mapper instanceof OIDCAccessTokenMapper) {
            token = ((OIDCAccessTokenMapper) mapper).transformAccessToken(token, mapping, session, userSession, clientSessionCtx);
        }
    }

    return token;
}
 
Example #19
Source File: AuthzCleanupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setup(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    session.getContext().setRealm(realm);
    AuthorizationProvider authz = session.getProvider(AuthorizationProvider.class);
    ClientModel myclient = realm.getClientByClientId("myclient");
    ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().findById(myclient.getId());
    createRolePolicy(authz, resourceServer, "client-role-1");
    createRolePolicy(authz, resourceServer, "client-role-2");
}
 
Example #20
Source File: PublicKeyStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static PublicKey getIdentityProviderPublicKey(KeycloakSession session, RealmModel realm, OIDCIdentityProviderConfig idpConfig, JWSInput input) {
    boolean keyIdSetInConfiguration = idpConfig.getPublicKeySignatureVerifierKeyId() != null
      && ! idpConfig.getPublicKeySignatureVerifierKeyId().trim().isEmpty();

    String kid = input.getHeader().getKeyId();

    PublicKeyStorageProvider keyStorage = session.getProvider(PublicKeyStorageProvider.class);

    String modelKey = PublicKeyStorageUtils.getIdpModelCacheKey(realm.getId(), idpConfig.getInternalId());
    PublicKeyLoader loader;
    if (idpConfig.isUseJwksUrl()) {
        loader = new OIDCIdentityProviderPublicKeyLoader(session, idpConfig);
    } else {
        String pem = idpConfig.getPublicKeySignatureVerifier();

        if (pem == null || pem.trim().isEmpty()) {
            logger.warnf("No public key saved on identityProvider %s", idpConfig.getAlias());
            return null;
        }

        loader = new HardcodedPublicKeyLoader(
          keyIdSetInConfiguration
            ? idpConfig.getPublicKeySignatureVerifierKeyId().trim()
            : kid, pem);
    }

    return (PublicKey)keyStorage.getPublicKey(modelKey, kid, loader).getPublicKey();
}
 
Example #21
Source File: CacheCommands.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRunCommand(KeycloakSession session) {
    String realmName = getArg(0);
    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Realm not found: %s", realmName);
        throw new HandledException();
    }

    TestCacheUtils.cacheRealmWithEverything(session, realmName);
}
 
Example #22
Source File: UserStorageSyncManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SynchronizationResult syncAllUsers(final KeycloakSessionFactory sessionFactory, final String realmId, final UserStorageProviderModel provider) {
    UserStorageProviderFactory factory = (UserStorageProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, provider.getProviderId());
    if (!(factory instanceof ImportSynchronization) || !provider.isImportEnabled() || !provider.isEnabled()) {
        return SynchronizationResult.ignored();

    }

    final Holder holder = new Holder();

    // Ensure not executed concurrently on this or any other cluster node
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            // shared key for "full" and "changed" . Improve if needed
            String taskKey = provider.getId() + "::sync";

            // 30 seconds minimal timeout for now
            int timeout = Math.max(30, provider.getFullSyncPeriod());
            holder.result = clusterProvider.executeIfNotExecuted(taskKey, timeout, new Callable<SynchronizationResult>() {

                @Override
                public SynchronizationResult call() throws Exception {
                    updateLastSyncInterval(sessionFactory, provider, realmId);
                    return ((ImportSynchronization)factory).sync(sessionFactory, realmId, provider);
                }

            });
        }

    });

    if (holder.result == null || !holder.result.isExecuted()) {
        logger.debugf("syncAllUsers for federation provider %s was ignored as it's already in progress", provider.getName());
        return SynchronizationResult.ignored();
    } else {
        return holder.result.getResult();
    }
}
 
Example #23
Source File: LinkedAccountsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SortedSet<LinkedAccountRepresentation> getLinkedAccounts(KeycloakSession session, RealmModel realm, UserModel user) {
    List<IdentityProviderModel> identityProviders = realm.getIdentityProviders();
    SortedSet<LinkedAccountRepresentation> linkedAccounts = new TreeSet<>();
    
    if (identityProviders == null || identityProviders.isEmpty()) return linkedAccounts;
    
    Set<String> socialIds = findSocialIds();
    Set<FederatedIdentityModel> identities = session.users().getFederatedIdentities(user, realm);
    for (IdentityProviderModel provider : identityProviders) {
        if (!provider.isEnabled()) {
            continue;
        }
        String providerId = provider.getAlias();

        FederatedIdentityModel identity = getIdentity(identities, providerId);

        String displayName = KeycloakModelUtils.getIdentityProviderDisplayName(session, provider);
        String guiOrder = provider.getConfig() != null ? provider.getConfig().get("guiOrder") : null;

        LinkedAccountRepresentation rep = new LinkedAccountRepresentation();
        rep.setConnected(identity != null);
        rep.setSocial(socialIds.contains(provider.getProviderId()));
        rep.setProviderAlias(providerId);
        rep.setDisplayName(displayName);
        rep.setGuiOrder(guiOrder);
        rep.setProviderName(provider.getAlias());
        if (identity != null) {
            rep.setLinkedUsername(identity.getUserName());
        }
        linkedAccounts.add(rep);
    }
    
    return linkedAccounts;
}
 
Example #24
Source File: SHA256PairwiseSubMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void validateAdditionalConfig(KeycloakSession session, RealmModel realm, ProtocolMapperContainerModel mapperContainer, ProtocolMapperModel mapperModel) throws ProtocolMapperConfigException {
    // Generate random salt if needed
    String salt = PairwiseSubMapperHelper.getSalt(mapperModel);
    if (salt == null || salt.trim().isEmpty()) {
        salt = generateSalt();
        PairwiseSubMapperHelper.setSalt(mapperModel, salt);
    }
}
 
Example #25
Source File: RolesPartialImport.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void prepareRealmRoles(PartialImportRepresentation rep, RealmModel realm, KeycloakSession session) throws ErrorResponseException {
    if (!rep.hasRealmRoles()) return;

    realmRolesPI.prepare(rep, realm, session);
    this.realmRolesToOverwrite = realmRolesPI.getToOverwrite();
    this.realmRolesToSkip = realmRolesPI.getToSkip();
}
 
Example #26
Source File: HardcodedAttributeMapperFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException {
    ConfigurationValidationHelper.check(config)
            .checkRequired(HardcodedAttributeMapper.USER_MODEL_ATTRIBUTE, "Attribute Name")
            .checkRequired(HardcodedAttributeMapper.ATTRIBUTE_VALUE, "Attribute Value");
    if(config.get(HardcodedAttributeMapper.USER_MODEL_ATTRIBUTE).equalsIgnoreCase("username") || config.get(HardcodedAttributeMapper.USER_MODEL_ATTRIBUTE).equalsIgnoreCase("email")){
        throw new ComponentValidationException("Attribute Name cannot be set to username or email");
    }
}
 
Example #27
Source File: ClientRoleMappingsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ClientRoleMappingsResource(UriInfo uriInfo, KeycloakSession session, RealmModel realm, AdminPermissionEvaluator auth,
                                  RoleMapperModel user, ClientModel client, AdminEventBuilder adminEvent,
                                  AdminPermissionEvaluator.RequirePermissionCheck manageCheck, AdminPermissionEvaluator.RequirePermissionCheck viewCheck ) {
    this.uriInfo = uriInfo;
    this.session = session;
    this.realm = realm;
    this.auth = auth;
    this.user = user;
    this.client = client;
    this.managePermission = manageCheck;
    this.viewPermission = viewCheck;
    this.adminEvent = adminEvent.resource(ResourceType.CLIENT_ROLE_MAPPING);
}
 
Example #28
Source File: RemoteCacheSessionListener.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void init(KeycloakSession session, Cache<K, SessionEntityWrapper<V>> cache, RemoteCache<K, SessionEntityWrapper<V>> remoteCache) {
    this.cache = cache;
    this.remoteCache = remoteCache;

    this.topologyInfo = InfinispanUtil.getTopologyInfo(session);

    ExecutorService executor = session.getProvider(ExecutorsProvider.class).getExecutor("client-listener-" + cache.getName());
    this.executor = new ClientListenerExecutorDecorator<>(executor);
}
 
Example #29
Source File: DBLockTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void simpleLockTest(KeycloakSession session) throws Exception {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionLC) -> {
        DBLockProvider dbLock = new DBLockManager(sessionLC).getDBLock();
        dbLock.waitForLock(DBLockProvider.Namespace.DATABASE);
        try {
            Assert.assertEquals(DBLockProvider.Namespace.DATABASE, dbLock.getCurrentLock());
        } finally {
            dbLock.releaseLock();
        }
        Assert.assertNull(dbLock.getCurrentLock());
    });
}
 
Example #30
Source File: AdminRoot.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Properties getMessages(KeycloakSession session, RealmModel realm, String lang, String... bundles) {
    Properties compound = new Properties();
    for (String bundle : bundles) {
        Properties current = getMessages(session, realm, lang, bundle);
        compound.putAll(current);
    }
    return compound;
}