Search in sources :

Example 11 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class ApplicationsBean method getApplications.

private Stream<ClientModel> getApplications(KeycloakSession session, RealmModel realm, UserModel user) {
    Predicate<ClientModel> bearerOnly = ClientModel::isBearerOnly;
    Stream<ClientModel> clients = realm.getClientsStream().filter(bearerOnly.negate());
    Predicate<ClientModel> isLocal = client -> new StorageId(client.getId()).isLocal();
    return Stream.concat(clients, session.users().getConsentsStream(realm, user.getId()).map(UserConsentModel::getClient).filter(isLocal.negate())).distinct();
}
Also used : ClientModel(org.keycloak.models.ClientModel) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) Predicate(java.util.function.Predicate) Constants(org.keycloak.models.Constants) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Collectors(java.util.stream.Collectors) StorageId(org.keycloak.storage.StorageId) ResolveRelative(org.keycloak.services.util.ResolveRelative) ArrayList(java.util.ArrayList) OrderedModel(org.keycloak.models.OrderedModel) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LinkedList(java.util.LinkedList) ClientModel(org.keycloak.models.ClientModel) StorageId(org.keycloak.storage.StorageId)

Example 12 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class SingleFileImportProvider method importModel.

@Override
public void importModel(KeycloakSessionFactory factory, final Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());
    checkRealmReps();
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            ImportUtils.importRealms(session, realmReps.values(), strategy);
        }
    });
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) ExportImportSessionTask(org.keycloak.exportimport.util.ExportImportSessionTask)

Example 13 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class LoginFormsUtil method filterIdentityProviders.

public static List<IdentityProviderModel> filterIdentityProviders(Stream<IdentityProviderModel> providers, KeycloakSession session, AuthenticationFlowContext context) {
    if (context != null) {
        AuthenticationSessionModel authSession = context.getAuthenticationSession();
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        final IdentityProviderModel existingIdp = (serializedCtx == null) ? null : serializedCtx.deserialize(session, authSession).getIdpConfig();
        final Set<String> federatedIdentities;
        if (context.getUser() != null) {
            federatedIdentities = session.users().getFederatedIdentitiesStream(session.getContext().getRealm(), context.getUser()).map(federatedIdentityModel -> federatedIdentityModel.getIdentityProvider()).collect(Collectors.toSet());
        } else {
            federatedIdentities = null;
        }
        return providers.filter(p -> {
            // Filter current IDP during first-broker-login flow. Re-authentication with the "linked" broker should not be possible
            if (existingIdp == null)
                return true;
            return !Objects.equals(p.getAlias(), existingIdp.getAlias());
        }).filter(idp -> {
            // In case that we already have user established in authentication session, we show just providers already linked to this user
            if (federatedIdentities == null)
                return true;
            return federatedIdentities.contains(idp.getAlias());
        }).collect(Collectors.toList());
    }
    return providers.collect(Collectors.toList());
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) AbstractIdpAuthenticator(org.keycloak.authentication.authenticators.broker.AbstractIdpAuthenticator) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) Collectors(java.util.stream.Collectors) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) Map(java.util.Map) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) AuthenticationFlowContext(org.keycloak.authentication.AuthenticationFlowContext) LinkedList(java.util.LinkedList) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) IdentityProviderModel(org.keycloak.models.IdentityProviderModel)

Example 14 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class AuthenticationManager method browserLogoutAllClients.

private static Response browserLogoutAllClients(UserSessionModel userSession, KeycloakSession session, RealmModel realm, HttpHeaders headers, UriInfo uriInfo, AuthenticationSessionModel logoutAuthSession) {
    Map<Boolean, List<AuthenticatedClientSessionModel>> acss = userSession.getAuthenticatedClientSessions().values().stream().filter(clientSession -> !Objects.equals(AuthenticationSessionModel.Action.LOGGED_OUT.name(), clientSession.getAction()) && !Objects.equals(AuthenticationSessionModel.Action.LOGGING_OUT.name(), clientSession.getAction())).filter(clientSession -> clientSession.getProtocol() != null).collect(Collectors.partitioningBy(clientSession -> clientSession.getClient().isFrontchannelLogout()));
    final List<AuthenticatedClientSessionModel> backendLogoutSessions = acss.get(false) == null ? Collections.emptyList() : acss.get(false);
    backendLogoutSessions.forEach(acs -> backchannelLogoutClientSession(session, realm, acs, logoutAuthSession, uriInfo, headers));
    final List<AuthenticatedClientSessionModel> redirectClients = acss.get(true) == null ? Collections.emptyList() : acss.get(true);
    for (AuthenticatedClientSessionModel nextRedirectClient : redirectClients) {
        Response response = frontchannelLogoutClientSession(session, realm, nextRedirectClient, logoutAuthSession, uriInfo, headers);
        if (response != null) {
            return response;
        }
    }
    return null;
}
Also used : DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ActionTokenStoreProvider(org.keycloak.models.ActionTokenStoreProvider) Error(org.keycloak.protocol.LoginProtocol.Error) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) Set(java.util.Set) AbstractUsernameFormAuthenticator(org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator) SecretGenerator(org.keycloak.common.util.SecretGenerator) Stream(java.util.stream.Stream) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) SessionTimeoutHelper(org.keycloak.models.utils.SessionTimeoutHelper) LoginActionsService(org.keycloak.services.resources.LoginActionsService) UriInfo(javax.ws.rs.core.UriInfo) OAuth2Constants(org.keycloak.OAuth2Constants) LoginProtocol(org.keycloak.protocol.LoginProtocol) Constants(org.keycloak.models.Constants) TokenManager(org.keycloak.protocol.oidc.TokenManager) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) Predicate(org.keycloak.TokenVerifier.Predicate) TokenVerifier(org.keycloak.TokenVerifier) CommonClientSessionModel(org.keycloak.sessions.CommonClientSessionModel) Base64Url(org.keycloak.common.util.Base64Url) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) ConsoleDisplayMode(org.keycloak.authentication.ConsoleDisplayMode) IdentityBrokerService(org.keycloak.services.resources.IdentityBrokerService) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails) HttpRequest(org.jboss.resteasy.spi.HttpRequest) EventType(org.keycloak.events.EventType) P3PHelper(org.keycloak.services.util.P3PHelper) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) URLDecoder(java.net.URLDecoder) ActionTokenKeyModel(org.keycloak.models.ActionTokenKeyModel) RequiredActionContextResult(org.keycloak.authentication.RequiredActionContextResult) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) NewCookie(javax.ws.rs.core.NewCookie) Messages(org.keycloak.services.messages.Messages) DefaultActionTokenKey(org.keycloak.authentication.actiontoken.DefaultActionTokenKey) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) URI(java.net.URI) SystemClientUtil(org.keycloak.models.utils.SystemClientUtil) VerificationException(org.keycloak.common.VerificationException) DeviceGrantType.isOAuth2DeviceVerificationFlow(org.keycloak.protocol.oidc.grants.device.DeviceGrantType.isOAuth2DeviceVerificationFlow) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) InitiatedActionSupport(org.keycloak.authentication.InitiatedActionSupport) AuthenticatorUtil(org.keycloak.authentication.AuthenticatorUtil) Collectors(java.util.stream.Collectors) Cookie(javax.ws.rs.core.Cookie) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ClientModel(org.keycloak.models.ClientModel) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) SameSiteAttributeValue(org.keycloak.common.util.ServerCookie.SameSiteAttributeValue) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ServicesLogger(org.keycloak.services.ServicesLogger) TokenTypeCheck(org.keycloak.TokenVerifier.TokenTypeCheck) RequiredActionContext(org.keycloak.authentication.RequiredActionContext) SignatureProvider(org.keycloak.crypto.SignatureProvider) EventBuilder(org.keycloak.events.EventBuilder) CookieHelper(org.keycloak.services.util.CookieHelper) UserConsentModel(org.keycloak.models.UserConsentModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) LinkedList(java.util.LinkedList) DisplayTypeRequiredActionFactory(org.keycloak.authentication.DisplayTypeRequiredActionFactory) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) Errors(org.keycloak.events.Errors) CORRESPONDING_SESSION_ID(org.keycloak.models.UserSessionModel.CORRESPONDING_SESSION_ID) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationContextUtil(org.keycloak.services.util.AuthorizationContextUtil) URLEncoder(java.net.URLEncoder) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) CookieHelper.getCookie(org.keycloak.services.util.CookieHelper.getCookie) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) List(java.util.List) LinkedList(java.util.LinkedList)

Example 15 with KeycloakSession

use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.

the class KeycloakSecurityHeadersFilter method filter.

@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) {
    KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);
    SecurityHeadersProvider securityHeadersProvider = session.getProvider(SecurityHeadersProvider.class);
    securityHeadersProvider.addHeaders(containerRequestContext, containerResponseContext);
}
Also used : KeycloakSession(org.keycloak.models.KeycloakSession) SecurityHeadersProvider(org.keycloak.headers.SecurityHeadersProvider)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14