Search in sources :

Example 26 with RealmModel

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

the class GeneratedHmacKeyProviderFactory method createFallbackKeys.

@Override
public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) {
    if (keyUse.equals(KeyUse.SIG) && (algorithm.equals(Algorithm.HS256) || algorithm.equals(Algorithm.HS384) || algorithm.equals(Algorithm.HS512))) {
        RealmModel realm = session.getContext().getRealm();
        ComponentModel generated = new ComponentModel();
        generated.setName("fallback-" + algorithm);
        generated.setParentId(realm.getId());
        generated.setProviderId(ID);
        generated.setProviderType(KeyProvider.class.getName());
        MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
        config.putSingle(Attributes.PRIORITY_KEY, "-100");
        config.putSingle(Attributes.ALGORITHM_KEY, algorithm);
        generated.setConfig(config);
        realm.addComponentModel(generated);
        return true;
    } else {
        return false;
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) ComponentModel(org.keycloak.component.ComponentModel)

Example 27 with RealmModel

use of org.keycloak.models.RealmModel 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 28 with RealmModel

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

the class AuthenticationManager method finishedRequiredActions.

public static Response finishedRequiredActions(KeycloakSession session, AuthenticationSessionModel authSession, UserSessionModel userSession, ClientConnection clientConnection, HttpRequest request, UriInfo uriInfo, EventBuilder event) {
    String actionTokenKeyToInvalidate = authSession.getAuthNote(INVALIDATE_ACTION_TOKEN);
    if (actionTokenKeyToInvalidate != null) {
        ActionTokenKeyModel actionTokenKey = DefaultActionTokenKey.from(actionTokenKeyToInvalidate);
        if (actionTokenKey != null) {
            ActionTokenStoreProvider actionTokenStore = session.getProvider(ActionTokenStoreProvider.class);
            // Token is invalidated
            actionTokenStore.put(actionTokenKey, null);
        }
    }
    if (authSession.getAuthNote(END_AFTER_REQUIRED_ACTIONS) != null) {
        LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.ACCOUNT_UPDATED);
        if (authSession.getAuthNote(SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS) != null) {
            if (authSession.getRedirectUri() != null) {
                infoPage.setAttribute("pageRedirectUri", authSession.getRedirectUri());
            }
        } else {
            infoPage.setAttribute(Constants.SKIP_LINK, true);
        }
        Response response = infoPage.createInfoPage();
        new AuthenticationSessionManager(session).removeAuthenticationSession(authSession.getRealm(), authSession, true);
        return response;
    }
    RealmModel realm = authSession.getRealm();
    ClientSessionContext clientSessionCtx = AuthenticationProcessor.attachSession(authSession, userSession, session, realm, clientConnection, event);
    userSession = clientSessionCtx.getClientSession().getUserSession();
    event.event(EventType.LOGIN);
    event.session(userSession);
    event.success();
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession);
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) RealmModel(org.keycloak.models.RealmModel) ActionTokenKeyModel(org.keycloak.models.ActionTokenKeyModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) ActionTokenStoreProvider(org.keycloak.models.ActionTokenStoreProvider) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext)

Example 29 with RealmModel

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

the class KeycloakErrorHandler method resolveRealm.

private RealmModel resolveRealm(KeycloakSession session) {
    String path = session.getContext().getUri().getPath();
    Matcher m = realmNamePattern.matcher(path);
    String realmName;
    if (m.matches()) {
        realmName = m.group(1);
    } else {
        realmName = Config.getAdminRealm();
    }
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        realm = realmManager.getRealmByName(Config.getAdminRealm());
    }
    session.getContext().setRealm(realm);
    return realm;
}
Also used : RealmModel(org.keycloak.models.RealmModel) Matcher(java.util.regex.Matcher) MediaTypeMatcher(org.keycloak.utils.MediaTypeMatcher) RealmManager(org.keycloak.services.managers.RealmManager)

Example 30 with RealmModel

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

the class ClientRegistrationPolicyManager method triggerPolicies.

private static void triggerPolicies(KeycloakSession session, ClientRegistrationProvider provider, RegistrationAuth authType, String opDescription, ClientRegOperation op) throws ClientRegistrationPolicyException {
    RealmModel realm = session.getContext().getRealm();
    String policyTypeKey = getComponentTypeKey(authType);
    realm.getComponentsStream(realm.getId(), ClientRegistrationPolicy.class.getName()).filter(componentModel -> Objects.equals(componentModel.getSubType(), policyTypeKey)).forEach(policyModel -> runPolicy(policyModel, session, provider, opDescription, op));
}
Also used : RealmModel(org.keycloak.models.RealmModel) Objects(java.util.Objects) ClientModel(org.keycloak.models.ClientModel) ClientRegistrationProvider(org.keycloak.services.clientregistration.ClientRegistrationProvider) RealmModel(org.keycloak.models.RealmModel) Details(org.keycloak.events.Details) ClientRegistrationContext(org.keycloak.services.clientregistration.ClientRegistrationContext) Logger(org.jboss.logging.Logger) ComponentModel(org.keycloak.component.ComponentModel) KeycloakSession(org.keycloak.models.KeycloakSession) ServicesLogger(org.keycloak.services.ServicesLogger)

Aggregations

RealmModel (org.keycloak.models.RealmModel)591 Test (org.junit.Test)249 UserModel (org.keycloak.models.UserModel)225 KeycloakSession (org.keycloak.models.KeycloakSession)152 ClientModel (org.keycloak.models.ClientModel)149 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)90 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)84 ComponentModel (org.keycloak.component.ComponentModel)83 RoleModel (org.keycloak.models.RoleModel)73 UserSessionModel (org.keycloak.models.UserSessionModel)64 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)62 List (java.util.List)55 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)51 GroupModel (org.keycloak.models.GroupModel)47 HashMap (java.util.HashMap)38 Collectors (java.util.stream.Collectors)34 CachedUserModel (org.keycloak.models.cache.CachedUserModel)34 Path (javax.ws.rs.Path)30 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)30 Map (java.util.Map)29