Java Code Examples for org.keycloak.models.KeycloakSession#getProvider()

The following examples show how to use org.keycloak.models.KeycloakSession#getProvider() . 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: MigrateTo4_6_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
    MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

    // Create "roles" and "web-origins" clientScopes
    ClientScopeModel rolesScope = migrationProvider.addOIDCRolesClientScope(realm);
    ClientScopeModel webOriginsScope = migrationProvider.addOIDCWebOriginsClientScope(realm);

    LOG.debugf("Added '%s' and '%s' default client scopes", rolesScope.getName(), webOriginsScope.getName());

    // Assign "roles" and "web-origins" clientScopes to all the OIDC clients
    for (ClientModel client : realm.getClients()) {
        if ((client.getProtocol()==null || "openid-connect".equals(client.getProtocol())) && (!client.isBearerOnly())) {
            client.addClientScope(rolesScope, true);
            client.addClientScope(webOriginsScope, true);
        }
    }

    LOG.debugf("Client scope '%s' assigned to all the clients", rolesScope.getName());
}
 
Example 2
Source File: OfflinePersistentUserSessionLoader.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public OfflinePersistentWorkerResult loadSessions(KeycloakSession session, OfflinePersistentLoaderContext loaderContext, OfflinePersistentWorkerContext ctx) {
    int first = ctx.getWorkerId() * sessionsPerSegment;

    log.tracef("Loading sessions for segment=%d createdOn=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastCreatedOn(), ctx.getLastSessionId());

    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
    List<UserSessionModel> sessions = persister.loadUserSessions(first, sessionsPerSegment, true, ctx.getLastCreatedOn(), ctx.getLastSessionId());

    log.tracef("Sessions loaded from DB - segment=%d createdOn=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastCreatedOn(), ctx.getLastSessionId());

    UserSessionModel lastSession = null;
    if (!sessions.isEmpty()) {
        lastSession = sessions.get(sessions.size() - 1);

        // Save to memory/infinispan
        session.sessions().importUserSessions(sessions, true);
    }

    int lastCreatedOn = lastSession==null ? Time.currentTime() + 100000 : lastSession.getStarted();
    String lastSessionId = lastSession==null ? FIRST_SESSION_ID : lastSession.getId();

    log.tracef("Sessions imported to infinispan - segment: %d, lastCreatedOn: %d, lastSessionId: %s", ctx.getSegment(), lastCreatedOn, lastSessionId);

    return new OfflinePersistentWorkerResult(true, ctx.getSegment(), ctx.getWorkerId(), lastCreatedOn, lastSessionId);
}
 
Example 3
Source File: InfinispanAuthenticationSessionProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (authSessionsCache == null) {
        synchronized (this) {
            if (authSessionsCache == null) {
                InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
                authSessionsCache = connections.getCache(InfinispanConnectionProvider.AUTHENTICATION_SESSIONS_CACHE_NAME);

                keyGenerator = new InfinispanKeyGenerator();

                ClusterProvider cluster = session.getProvider(ClusterProvider.class);
                cluster.registerListener(AUTHENTICATION_SESSION_EVENTS, this::updateAuthNotes);

                log.debugf("[%s] Registered cluster listeners", authSessionsCache.getCacheManager().getAddress());
            }
        }
    }
}
 
Example 4
Source File: InfinispanCodeToTokenStoreProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (codeCache == null) {
        synchronized (this) {
            if (codeCache == null) {
                InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
                Cache cache = connections.getCache(InfinispanConnectionProvider.ACTION_TOKEN_CACHE);

                RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

                if (remoteCache != null) {
                    LOG.debugf("Having remote stores. Using remote cache '%s' for single-use cache of code", remoteCache.getName());
                    this.codeCache = () -> {
                        // Doing this way as flag is per invocation
                        return remoteCache.withFlags(Flag.FORCE_RETURN_VALUE);
                    };
                } else {
                    LOG.debugf("Not having remote stores. Using normal cache '%s' for single-use cache of code", cache.getName());
                    this.codeCache = () -> {
                        return cache;
                    };
                }
            }
        }
    }
}
 
Example 5
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void testCheckUserRealmRoles(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("testCheckUserRealmRoles");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var roles = realm.getUserRealmRoles('marta');");
    builder.append("if (roles.size() == 2 && roles.contains('uma_authorization') && roles.contains('role-a')) { $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 6
Source File: AbstractResourceService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AbstractResourceService(KeycloakSession session, UserModel user, Auth auth, HttpRequest request) {
    this.user = user;
    this.auth = auth;
    this.request = request;
    provider = session.getProvider(AuthorizationProvider.class);
    ticketStore = provider.getStoreFactory().getPermissionTicketStore();
    resourceStore = provider.getStoreFactory().getResourceStore();
    scopeStore = provider.getStoreFactory().getScopeStore();
    uriInfo = session.getContext().getUri();
}
 
Example 7
Source File: InfinispanUserSessionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public InfinispanUserSessionProvider create(KeycloakSession session) {
    InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = connections.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionsCache = connections.getCache(InfinispanConnectionProvider.OFFLINE_USER_SESSION_CACHE_NAME);
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache = connections.getCache(InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME);
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionsCache = connections.getCache(InfinispanConnectionProvider.OFFLINE_CLIENT_SESSION_CACHE_NAME);
    Cache<LoginFailureKey, SessionEntityWrapper<LoginFailureEntity>> loginFailures = connections.getCache(InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME);

    return new InfinispanUserSessionProvider(session, remoteCacheInvoker, lastSessionRefreshStore, offlineLastSessionRefreshStore,
            persisterLastSessionRefreshStore, keyGenerator,
      cache, offlineSessionsCache, clientSessionCache, offlineClientSessionsCache, loginFailures);
}
 
Example 8
Source File: DefaultJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
void migration(MigrationStrategy strategy, boolean initializeEmpty, String schema, File databaseUpdateFile, Connection connection, KeycloakSession session) {
    JpaUpdaterProvider updater = session.getProvider(JpaUpdaterProvider.class);

    JpaUpdaterProvider.Status status = updater.validate(connection, schema);
    if (status == JpaUpdaterProvider.Status.VALID) {
        logger.debug("Database is up-to-date");
    } else if (status == JpaUpdaterProvider.Status.EMPTY) {
        if (initializeEmpty) {
            update(connection, schema, session, updater);
        } else {
            switch (strategy) {
                case UPDATE:
                    update(connection, schema, session, updater);
                    break;
                case MANUAL:
                    export(connection, schema, databaseUpdateFile, session, updater);
                    throw new ServerStartupError("Database not initialized, please initialize database with " + databaseUpdateFile.getAbsolutePath(), false);
                case VALIDATE:
                    throw new ServerStartupError("Database not initialized, please enable database initialization", false);
            }
        }
    } else {
        switch (strategy) {
            case UPDATE:
                update(connection, schema, session, updater);
                break;
            case MANUAL:
                export(connection, schema, databaseUpdateFile, session, updater);
                throw new ServerStartupError("Database not up-to-date, please migrate database with " + databaseUpdateFile.getAbsolutePath(), false);
            case VALIDATE:
                throw new ServerStartupError("Database not up-to-date, please enable database migration", false);
        }
    }
}
 
Example 9
Source File: MtlsHoKTokenUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate[] getCertificateChain(HttpRequest request, KeycloakSession session) {
    try {
           // Get a x509 client certificate
        X509ClientCertificateLookup provider = session.getProvider(X509ClientCertificateLookup.class);
        if (provider == null) {
            logger.errorv("\"{0}\" Spi is not available, did you forget to update the configuration?", X509ClientCertificateLookup.class);
        return null;
        }
        X509Certificate[] certs = provider.getCertificateChain(request);
        return certs;
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 10
Source File: AuthorizationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AuthorizationService(KeycloakSession session, ClientModel client, AdminPermissionEvaluator auth, AdminEventBuilder adminEvent) {
    this.client = client;
    this.authorization = session.getProvider(AuthorizationProvider.class);
    this.adminEvent = adminEvent;
    this.resourceServer = this.authorization.getStoreFactory().getResourceServerStore().findById(this.client.getId());
    this.auth = auth;
}
 
Example 11
Source File: ClearExpiredEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void run(KeycloakSession session) {
    EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
    if (eventStore != null) {
        for (RealmModel realm : session.realms().getRealms()) {
            if (realm.isEventsEnabled() && realm.getEventsExpiration() > 0) {
                long olderThan = System.currentTimeMillis() - realm.getEventsExpiration() * 1000;
                eventStore.clear(realm.getId(), olderThan);
            }
        }
    }
}
 
Example 12
Source File: KeycloakSecurityHeadersFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);
    SecurityHeadersProvider securityHeadersProvider = session.getProvider(SecurityHeadersProvider.class);
    securityHeadersProvider.addHeaders(requestContext, responseContext);
}
 
Example 13
Source File: PasswordForm.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public PasswordCredentialProvider getCredentialProvider(KeycloakSession session) {
    return (PasswordCredentialProvider)session.getProvider(CredentialProvider.class, "keycloak-password");
}
 
Example 14
Source File: JpaEventStoreProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public EventStoreProvider create(KeycloakSession session) {
    JpaConnectionProvider connection = session.getProvider(JpaConnectionProvider.class);
    return new JpaEventStoreProvider(connection.getEntityManager(), maxDetailLength);
}
 
Example 15
Source File: CacheCommands.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void doRunCommand(KeycloakSession session) {
    InfinispanConnectionProvider ispnProvider = session.getProvider(InfinispanConnectionProvider.class);
    Set<String> cacheNames = ispnProvider.getCache("realms").getCacheManager().getCacheNames();
    log.infof("Available caches: %s", cacheNames);
}
 
Example 16
Source File: LDAPTestUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static LDAPStorageProvider getLdapProvider(KeycloakSession keycloakSession, ComponentModel ldapFedModel) {
    return (LDAPStorageProvider)keycloakSession.getProvider(UserStorageProvider.class, ldapFedModel);
}
 
Example 17
Source File: EmailEventListenerProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public EventListenerProvider create(KeycloakSession session) {
    EmailTemplateProvider emailTemplateProvider = session.getProvider(EmailTemplateProvider.class);
    return new EmailEventListenerProvider(session, emailTemplateProvider, includedEvents);
}
 
Example 18
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void testCachedDecisionsWithNegativePolicies(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());

    Scope readScope = storeFactory.getScopeStore().create("read", resourceServer);
    Scope writeScope = storeFactory.getScopeStore().create("write", resourceServer);

    JSPolicyRepresentation policy = new JSPolicyRepresentation();

    policy.setName(KeycloakModelUtils.generateId());
    policy.setCode("$evaluation.grant()");
    policy.setLogic(Logic.NEGATIVE);

    storeFactory.getPolicyStore().create(policy, resourceServer);

    ScopePermissionRepresentation readPermission = new ScopePermissionRepresentation();

    readPermission.setName(KeycloakModelUtils.generateId());
    readPermission.addScope(readScope.getId());
    readPermission.addPolicy(policy.getName());

    storeFactory.getPolicyStore().create(readPermission, resourceServer);

    ScopePermissionRepresentation writePermission = new ScopePermissionRepresentation();

    writePermission.setName(KeycloakModelUtils.generateId());
    writePermission.addScope(writeScope.getId());
    writePermission.addPolicy(policy.getName());

    storeFactory.getPolicyStore().create(writePermission, resourceServer);

    Resource resource = storeFactory.getResourceStore().create(KeycloakModelUtils.generateId(), resourceServer, resourceServer.getId());

    PermissionEvaluator evaluator = authorization.evaluators().from(Arrays.asList(new ResourcePermission(resource, Arrays.asList(readScope, writeScope), resourceServer)), createEvaluationContext(session, Collections.emptyMap()));
    Collection<Permission> permissions = evaluator.evaluate(resourceServer, null);

    Assert.assertEquals(0, permissions.size());
}
 
Example 19
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
public static void testCheckUserInRole(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("testCheckUserInRole");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("if (realm.isUserInRealmRole('marta', 'role-a')) { $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());

    builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("if (realm.isUserInRealmRole('marta', 'role-b')) { $evaluation.grant(); }");

    policyRepresentation.setCode(builder.toString());

    policyRepresentation.setId(policy.getId());
    policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);

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

    provider.evaluate(evaluation);

    Assert.assertNull(evaluation.getEffect());
}
 
Example 20
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
public static void testCheckUserInClientRole(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("testCheckUserInClientRole");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("if (realm.isUserInClientRole('trinity', 'role-mapping-client', 'client-role-a')) { $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());

    builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("if (realm.isUserInRealmRole('trinity', 'client-role-b')) { $evaluation.grant(); }");

    policyRepresentation.setCode(builder.toString());

    policyRepresentation.setId(policy.getId());
    policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);

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

    provider.evaluate(evaluation);

    Assert.assertNull(evaluation.getEffect());
}