Java源码示例:org.keycloak.sessions.AuthenticationSessionModel

示例1
public static List<IdentityProviderModel> filterIdentityProviders(List<IdentityProviderModel> providers, KeycloakSession session, RealmModel realm,
                                                                  Map<String, Object> attributes, MultivaluedMap<String, String> formData, AuthenticationFlowContext context) {

    if (context != null) {
        AuthenticationSessionModel authSession = context.getAuthenticationSession();
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);

        if (serializedCtx != null) {
            IdentityProviderModel idp = serializedCtx.deserialize(session, authSession).getIdpConfig();
            return providers.stream()
                    .filter(p -> !Objects.equals(p.getAlias(), idp.getAlias()))
                    .collect(Collectors.toList());
        }
    }
    return providers;
}
 
示例2
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    String existingUserInfo = authSession.getAuthNote(EXISTING_USER_INFO);
    if (existingUserInfo == null) {
        ServicesLogger.LOGGER.noDuplicationDetected();
        context.attempted();
        return;
    }

    ExistingUserInfo duplicationInfo = ExistingUserInfo.deserialize(existingUserInfo);
    Response challenge = context.form()
            .setStatus(Response.Status.OK)
            .setAttribute(LoginFormsProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext)
            .setError(Messages.FEDERATED_IDENTITY_CONFIRM_LINK_MESSAGE, duplicationInfo.getDuplicateAttributeName(), duplicationInfo.getDuplicateAttributeValue())
            .createIdpLinkConfirmLinkPage();
    context.challenge(challenge);
}
 
示例3
/**
 * Verifies that the authentication session has not yet been converted to user session, in other words
 * that the user has not yet completed authentication and logged in.
 */
public static <T extends JsonWebToken> void checkNotLoggedInYet(ActionTokenContext<T> context, AuthenticationSessionModel authSessionFromCookie, String authSessionId) throws VerificationException {
    if (authSessionId == null) {
        return;
    }

    UserSessionModel userSession = context.getSession().sessions().getUserSession(context.getRealm(), authSessionId);
    boolean hasNoRequiredActions =
      (userSession == null || userSession.getUser().getRequiredActions() == null || userSession.getUser().getRequiredActions().isEmpty())
      &&
      (authSessionFromCookie == null || authSessionFromCookie.getRequiredActions() == null || authSessionFromCookie.getRequiredActions().isEmpty());

    if (userSession != null && hasNoRequiredActions) {
        LoginFormsProvider loginForm = context.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(context.getAuthenticationSession())
          .setSuccess(Messages.ALREADY_LOGGED_IN);

        if (context.getSession().getContext().getClient() == null) {
            loginForm.setAttribute(Constants.SKIP_LINK, true);
        }

        throw new LoginActionsServiceException(loginForm.createInfoPage());
    }
}
 
示例4
@Override
public void authenticate(AuthenticationFlowContext context) {
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(context.getSession(),
            context.getRealm(), true);
    if (authResult == null) {
        context.attempted();
    } else {
        AuthenticationSessionModel clientSession = context.getAuthenticationSession();
        LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, clientSession.getProtocol());

        // Cookie re-authentication is skipped if re-authentication is required
        if (protocol.requireReauthentication(authResult.getSession(), clientSession)) {
            context.attempted();
        } else {
            context.getSession().setAttribute(AuthenticationManager.SSO_AUTH, "true");

            context.setUser(authResult.getUser());
            context.attachUserSession(authResult.getSession());
            context.success();
        }
    }

}
 
示例5
public AuthenticationSessionEntity(
  String clientUUID,
  String authUserId,
  String redirectUri, String action, Set<String> clientScopes,
  Map<String, AuthenticationSessionModel.ExecutionStatus> executionStatus, String protocol,
  Map<String, String> clientNotes, Map<String, String> authNotes, Set<String> requiredActions, Map<String, String> userSessionNotes) {
    this.clientUUID = clientUUID;

    this.authUserId = authUserId;

    this.redirectUri = redirectUri;
    this.action = action;
    this.clientScopes = clientScopes;

    this.executionStatus = executionStatus;
    this.protocol = protocol;

    this.clientNotes = clientNotes;
    this.authNotes = authNotes;
    this.requiredActions = requiredActions;
    this.userSessionNotes = userSessionNotes;
}
 
示例6
private static void backchannelLogoutAll(KeycloakSession session, RealmModel realm,
  UserSessionModel userSession, AuthenticationSessionModel logoutAuthSession, UriInfo uriInfo,
  HttpHeaders headers, boolean logoutBroker) {
    userSession.getAuthenticatedClientSessions().values().forEach(
      clientSession -> backchannelLogoutClientSession(session, realm, clientSession, logoutAuthSession, uriInfo, headers)
    );
    if (logoutBroker) {
        String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
        if (brokerId != null) {
            IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
            try {
                identityProvider.backchannelLogout(session, userSession, uriInfo, realm);
            } catch (Exception e) {
                logger.warn("Exception at broker backchannel logout for broker " + brokerId, e);
            }
        }
    }
}
 
示例7
@Override
public void requiredActionChallenge(RequiredActionContext context) {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    if (context.getUser().isEmailVerified()) {
        context.success();
        authSession.removeAuthNote(Constants.VERIFY_EMAIL_KEY);
        return;
    }

    String email = context.getUser().getEmail();
    if (Validation.isBlank(email)) {
        context.ignore();
        return;
    }

    Response challenge = sendVerifyEmail(context);
    context.challenge(challenge);
}
 
示例8
/**
 * protocol independent page for restart of the flow
 *
 * @return
 */
@Path(RESTART_PATH)
@GET
public Response restartSession(@QueryParam(AUTH_SESSION_ID) String authSessionId, // optional, can get from cookie instead
                               @QueryParam(Constants.CLIENT_ID) String clientId,
                               @QueryParam(Constants.TAB_ID) String tabId) {
    event.event(EventType.RESTART_AUTHENTICATION);
    SessionCodeChecks checks = new SessionCodeChecks(realm, session.getContext().getUri(), request, clientConnection, session, event, authSessionId, null, null, clientId,  tabId, null);

    AuthenticationSessionModel authSession = checks.initialVerifyAuthSession();
    if (authSession == null) {
        return checks.getResponse();
    }

    String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
    if (flowPath == null) {
        flowPath = AUTHENTICATE_PATH;
    }

    AuthenticationProcessor.resetFlow(authSession, flowPath);

    URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getClient().getClientId(), tabId);
    logger.debugf("Flow restart requested. Redirecting to %s", redirectUri);
    return Response.status(Response.Status.FOUND).location(redirectUri).build();
}
 
示例9
private boolean conditionalNotMatched(AuthenticationExecutionModel model, List<AuthenticationExecutionModel> executionList) {
    AuthenticatorFactory factory = getAuthenticatorFactory(model);
    ConditionalAuthenticator authenticator = (ConditionalAuthenticator) createAuthenticator(factory);
    AuthenticationProcessor.Result context = processor.createAuthenticatorContext(model, authenticator, executionList);

   boolean matchCondition;

    // Retrieve previous evaluation result if any, else evaluate and store result for future re-evaluation
    if (processor.isEvaluatedTrue(model)) {
        matchCondition = true;
    } else if (processor.isEvaluatedFalse(model)) {
        matchCondition = false;
    } else {
        matchCondition = authenticator.matchCondition(context);
        processor.getAuthenticationSession().setExecutionStatus(model.getId(),
                matchCondition ? AuthenticationSessionModel.ExecutionStatus.EVALUATED_TRUE : AuthenticationSessionModel.ExecutionStatus.EVALUATED_FALSE);
    }

    return !matchCondition;
}
 
示例10
protected boolean isAuthTimeExpired(UserSessionModel userSession, AuthenticationSessionModel authSession) {
    String authTime = userSession.getNote(AuthenticationManager.AUTH_TIME);
    String maxAge = authSession.getClientNote(OIDCLoginProtocol.MAX_AGE_PARAM);
    if (maxAge == null) {
        return false;
    }

    int authTimeInt = authTime==null ? 0 : Integer.parseInt(authTime);
    int maxAgeInt = Integer.parseInt(maxAge);

    if (authTimeInt + maxAgeInt < Time.currentTime()) {
        logger.debugf("Authentication time is expired, needs to reauthenticate. userSession=%s, clientId=%s, maxAge=%d, authTime=%d", userSession.getId(),
                authSession.getClient().getId(), maxAgeInt, authTimeInt);
        return true;
    }

    return false;
}
 
示例11
private static List<ClientScopeModel> getClientScopesToApproveOnConsentScreen(RealmModel realm, UserConsentModel grantedConsent,
                                                                              AuthenticationSessionModel authSession) {
    // Client Scopes to be displayed on consent screen
    List<ClientScopeModel> clientScopesToDisplay = new LinkedList<>();

    for (String clientScopeId : authSession.getClientScopes()) {
        ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, authSession.getClient(), clientScopeId);

        if (clientScope == null || !clientScope.isDisplayOnConsentScreen()) {
            continue;
        }

        // Check if consent already granted by user
        if (grantedConsent == null || !grantedConsent.isClientScopeGranted(clientScope)) {
            clientScopesToDisplay.add(clientScope);
        }
    }

    return clientScopesToDisplay;
}
 
示例12
private boolean shouldPerformAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, String providerId) {
    String noteFromSession = authSession.getAuthNote(LINKING_IDENTITY_PROVIDER);
    if (noteFromSession == null) {
        return false;
    }

    boolean linkingValid;
    if (userSession == null) {
        linkingValid = false;
    } else {
        String expectedNote = userSession.getId() + authSession.getClient().getClientId() + providerId;
        linkingValid = expectedNote.equals(noteFromSession);
    }

    if (linkingValid) {
        authSession.removeAuthNote(LINKING_IDENTITY_PROVIDER);
        return true;
    } else {
        throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.BROKER_LINKING_SESSION_EXPIRED);
    }
}
 
示例13
private Response finishBrokerAuthentication(BrokeredIdentityContext context, UserModel federatedUser, AuthenticationSessionModel authSession, String providerId) {
    authSession.setAuthNote(AuthenticationProcessor.BROKER_SESSION_ID, context.getBrokerSessionId());
    authSession.setAuthNote(AuthenticationProcessor.BROKER_USER_ID, context.getBrokerUserId());

    this.event.user(federatedUser);

    context.getIdp().authenticationFinished(authSession, context);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER, providerId);
    authSession.setUserSessionNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    event.detail(Details.IDENTITY_PROVIDER, providerId)
            .detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

    if (isDebugEnabled()) {
        logger.debugf("Performing local authentication for user [%s].", federatedUser);
    }

    AuthenticationManager.setClientScopesInSession(authSession);

    String nextRequiredAction = AuthenticationManager.nextRequiredAction(session, authSession, clientConnection, request, session.getContext().getUri(), event);
    if (nextRequiredAction != null) {
        if ("true".equals(authSession.getAuthNote(AuthenticationProcessor.FORWARDED_PASSIVE_LOGIN))) {
            logger.errorf("Required action %s found. Auth requests using prompt=none are incompatible with required actions", nextRequiredAction);
            return checkPassiveLoginError(authSession, OAuthErrorException.INTERACTION_REQUIRED);
        }
        return AuthenticationManager.redirectToRequiredActions(session, realmModel, authSession, session.getContext().getUri(), nextRequiredAction);
    } else {
        event.detail(Details.CODE_ID, authSession.getParentSession().getId());  // todo This should be set elsewhere.  find out why tests fail.  Don't know where this is supposed to be set
        return AuthenticationManager.finishedRequiredActions(session, authSession, null, clientConnection, request, session.getContext().getUri(), event);
    }
}
 
示例14
private Response processFlowFromPath(String flowPath, AuthenticationSessionModel authSession, String errorMessage) {
    if (AUTHENTICATE_PATH.equals(flowPath)) {
        return processAuthentication(false, null, authSession, errorMessage);
    } else if (REGISTRATION_PATH.equals(flowPath)) {
        return processRegistration(false, null, authSession, errorMessage);
    } else if (RESET_CREDENTIALS_PATH.equals(flowPath)) {
        return processResetCredentials(false, null, authSession, errorMessage);
    } else {
        return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, errorMessage == null ? Messages.INVALID_REQUEST : errorMessage);
    }
}
 
示例15
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);

}
 
示例16
@Override
public Response cancelled(String code) {
    ParsedCodeContext parsedCode = parseEncodedSessionCode(code);
    if (parsedCode.response != null) {
        return parsedCode.response;
    }
    ClientSessionCode<AuthenticationSessionModel> clientCode = parsedCode.clientSessionCode;

    Response accountManagementFailedLinking = checkAccountManagementFailedLinking(clientCode.getClientSession(), Messages.CONSENT_DENIED);
    if (accountManagementFailedLinking != null) {
        return accountManagementFailedLinking;
    }

    return browserAuthentication(clientCode.getClientSession(), null);
}
 
示例17
public void saveToAuthenticationSession(AuthenticationSessionModel authSession, String noteKey) {
    try {
        String asString = JsonSerialization.writeValueAsString(this);
        authSession.setAuthNote(noteKey, asString);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
示例18
public static Response browserLogout(KeycloakSession session,
                                     RealmModel realm,
                                     UserSessionModel userSession,
                                     UriInfo uriInfo,
                                     ClientConnection connection,
                                     HttpHeaders headers,
                                     String initiatingIdp) {
    if (userSession == null) return null;

    if (logger.isDebugEnabled()) {
        UserModel user = userSession.getUser();
        logger.debugv("Logging out: {0} ({1})", user.getUsername(), userSession.getId());
    }
    
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

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

    Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession);
    if (response != null) {
        return response;
    }

    String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
    if (brokerId != null && !brokerId.equals(initiatingIdp)) {
        IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
        response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm);
        if (response != null) {
            return response;
        }
    }

    return finishBrowserLogout(session, realm, userSession, uriInfo, connection, headers);
}
 
示例19
private AuthenticationRequest createAuthenticationRequest(String providerId, ClientSessionCode<AuthenticationSessionModel> clientSessionCode) {
    AuthenticationSessionModel authSession = null;
    IdentityBrokerState encodedState = null;

    if (clientSessionCode != null) {
        authSession = clientSessionCode.getClientSession();
        String relayState = clientSessionCode.getOrGenerateCode();
        encodedState = IdentityBrokerState.decoded(relayState, authSession.getClient().getClientId(), authSession.getTabId());
    }

    return new AuthenticationRequest(this.session, this.realmModel, authSession, this.request, this.session.getContext().getUri(), encodedState, getRedirectUri(providerId));
}
 
示例20
public static AuthenticationFlowModel resolveBrowserFlow(AuthenticationSessionModel authSession) {
    AuthenticationFlowModel flow = null;
    ClientModel client = authSession.getClient();
    String clientFlow = client.getAuthenticationFlowBindingOverride(AuthenticationFlowBindings.BROWSER_BINDING);
    if (clientFlow != null) {
        flow = authSession.getRealm().getAuthenticationFlowById(clientFlow);
        if (flow == null) {
            throw new ModelException("Client " + client.getClientId() + " has browser flow override, but this flow does not exist");
        }
        return flow;
    }
    return authSession.getRealm().getBrowserFlow();
}
 
示例21
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);
            actionTokenStore.put(actionTokenKey, null); // Token is invalidated
        }
    }

    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);
}
 
示例22
public static SerializedBrokeredIdentityContext readFromAuthenticationSession(AuthenticationSessionModel authSession, String noteKey) {
    String asString = authSession.getAuthNote(noteKey);
    if (asString == null) {
        return null;
    } else {
        try {
            SerializedBrokeredIdentityContext serializedCtx = JsonSerialization.readValue(asString, SerializedBrokeredIdentityContext.class);
            serializedCtx.emailAsUsername = authSession.getRealm().isRegistrationEmailAsUsername();
            return serializedCtx;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }
}
 
示例23
public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession,
                                                   ClientSessionContext clientSessionCtx,
                                            HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,
                                            EventBuilder event, AuthenticationSessionModel authSession) {
    LoginProtocol protocolImpl = session.getProvider(LoginProtocol.class, authSession.getProtocol());
    protocolImpl.setRealm(realm)
            .setHttpHeaders(request.getHttpHeaders())
            .setUriInfo(uriInfo)
            .setEventBuilder(event);
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession, protocolImpl);

}
 
示例24
public AuthenticationRequest(KeycloakSession session, RealmModel realm, AuthenticationSessionModel authSession, HttpRequest httpRequest, UriInfo uriInfo, IdentityBrokerState state, String redirectUri) {
    this.session = session;
    this.realm = realm;
    this.httpRequest = httpRequest;
    this.uriInfo = uriInfo;
    this.state = state;
    this.redirectUri = redirectUri;
    this.authSession = authSession;
}
 
示例25
public void removeAuthenticationSession(RealmModel realm, AuthenticationSessionModel authSession, boolean expireRestartCookie) {
    RootAuthenticationSessionModel rootAuthSession = authSession.getParentSession();

    log.debugf("Removing authSession '%s'. Expire restart cookie: %b", rootAuthSession.getId(), expireRestartCookie);
    session.authenticationSessions().removeRootAuthenticationSession(realm, rootAuthSession);

    // expire restart cookie
    if (expireRestartCookie) {
        ClientConnection clientConnection = session.getContext().getConnection();
        UriInfo uriInfo = session.getContext().getUri();
        RestartLoginCookie.expireRestartCookie(realm, clientConnection, uriInfo);
    }
}
 
示例26
@Test
@ModelTest
public  void testIsLoginTimeoutValid(KeycloakSession keycloakSession) {
    
    RealmModel realm = keycloakSession.realms().getRealmByName("test");
    UserSessionModel userSession =
        keycloakSession.sessions().createUserSession(
                                             realm,
                                             keycloakSession.users().getUserByUsername("user1", realm),
                                             "user1", "127.0.0.1", "form", true, null, null
                                             );
    ClientModel client = realm.getClientByClientId("account");
    AuthenticationSessionModel authSession = keycloakSession.authenticationSessions().createRootAuthenticationSession(realm)
        .createAuthenticationSession(client);
    ClientSessionCode clientSessionCode = new ClientSessionCode(keycloakSession, realm, authSession);

    /*
     * KEYCLOAK-10636 Large Login timeout causes login failure
     * realm > Realm setting > Tokens > Login timeout
     */
    int accessCodeLifespanLoginOrig = realm.getAccessCodeLifespanLogin(); // Login timeout
    realm.setAccessCodeLifespanLogin(Integer.MAX_VALUE);
    Assert.assertTrue("Login validataion with large Login Timeout failed",
                      clientSessionCode.isActionActive(ClientSessionCode.ActionType.LOGIN));
    realm.setAccessCodeLifespanLogin(accessCodeLifespanLoginOrig);

    /*
     * KEYCLOAK-10637 Large Login Action timeout causes login failure
     * realm > Realm setting > Tokens > Login Action timeout
     */
    int accessCodeLifespanUserActionOrig = realm.getAccessCodeLifespanUserAction(); // Login Action timeout
    realm.setAccessCodeLifespanUserAction(Integer.MAX_VALUE);
    Assert.assertTrue("Login validataion with large Login Action Timeout failed",
                      clientSessionCode.isActionActive(ClientSessionCode.ActionType.USER));
    realm.setAccessCodeLifespanUserAction(accessCodeLifespanUserActionOrig);
}
 
示例27
private void testAuthenticationSession(AuthenticationSessionModel authSession, String expectedClientId, String expectedUserId, String expectedAction) {
    assertThat(authSession.getClient().getId(), is(expectedClientId));

    if (expectedUserId == null) {
        assertThat(authSession.getAuthenticatedUser(), nullValue());
    } else {
        assertThat(authSession.getAuthenticatedUser().getId(), is(expectedUserId));
    }

    if (expectedAction == null) {
        assertThat(authSession.getAction(), nullValue());
    } else {
        assertThat(authSession.getAction(), is(expectedAction));
    }
}
 
示例28
private static UserConsentModel getEffectiveGrantedConsent(KeycloakSession session, AuthenticationSessionModel authSession) {
    // If prompt=consent, we ignore existing persistent consent
    String prompt = authSession.getClientNote(OIDCLoginProtocol.PROMPT_PARAM);
    if (TokenUtil.hasPrompt(prompt, OIDCLoginProtocol.PROMPT_VALUE_CONSENT)) {
        return null;
    } else {
        final RealmModel realm = authSession.getRealm();
        final UserModel user = authSession.getAuthenticatedUser();
        final ClientModel client = authSession.getClient();

        return session.users().getConsentByClient(realm, user.getId(), client.getId());
    }
}
 
示例29
private static AuthenticationSessionModel createOrJoinLogoutSession(KeycloakSession session, RealmModel realm, final AuthenticationSessionManager asm, UserSessionModel userSession, boolean browserCookie) {
    // Account management client is used as a placeholder
    ClientModel client = SystemClientUtil.getSystemClient(realm);

    String authSessionId;
    RootAuthenticationSessionModel rootLogoutSession = null;
    boolean browserCookiePresent = false;

    // Try to lookup current authSessionId from browser cookie. If doesn't exists, use the same as current userSession
    if (browserCookie) {
        rootLogoutSession = asm.getCurrentRootAuthenticationSession(realm);
    }
    if (rootLogoutSession != null) {
        authSessionId = rootLogoutSession.getId();
        browserCookiePresent = true;
    } else {
        authSessionId = userSession.getId();
        rootLogoutSession = session.authenticationSessions().getRootAuthenticationSession(realm, authSessionId);
    }

    if (rootLogoutSession == null) {
        rootLogoutSession = session.authenticationSessions().createRootAuthenticationSession(authSessionId, realm);
    }
    if (browserCookie && !browserCookiePresent) {
        // Update cookie if needed
        asm.setAuthSessionCookie(authSessionId, realm);
    }

    // See if we have logoutAuthSession inside current rootSession. Create new if not
    Optional<AuthenticationSessionModel> found = rootLogoutSession.getAuthenticationSessions().values().stream().filter((AuthenticationSessionModel authSession) -> {
        return client.equals(authSession.getClient()) && Objects.equals(AuthenticationSessionModel.Action.LOGGING_OUT.name(), authSession.getAction());

    }).findFirst();

    AuthenticationSessionModel logoutAuthSession = found.isPresent() ? found.get() : rootLogoutSession.createAuthenticationSession(client);
    session.getContext().setAuthenticationSession(logoutAuthSession);

    logoutAuthSession.setAction(AuthenticationSessionModel.Action.LOGGING_OUT.name());
    return logoutAuthSession;
}
 
示例30
public static UserModel lookupUserForBruteForceLog(KeycloakSession session, RealmModel realm, AuthenticationSessionModel authenticationSession) {
    UserModel user = authenticationSession.getAuthenticatedUser();
    if (user != null) return user;

    String username = authenticationSession.getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    if (username != null) {
        return KeycloakModelUtils.findUserByNameOrEmail(session, realm, username);
    }

    return null;
}