Java Code Examples for org.keycloak.authentication.AuthenticationFlowContext#resetFlow()

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#resetFlow() . 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: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    UserModel user = context.getUser();
    if (user == null) {
        context.attempted();
        return;
    }

    String targetIdp = determineTargetIdp(user, context);
    if (targetIdp != null) {
        redirect(context, targetIdp);
        return;
    }

    boolean fallbackToAuthFlow = getConfigValueOrDefault(context.getAuthenticatorConfig(), FALLBACK_TO_AUTHFLOW_CONFIG_PROPERTY, "true", Boolean::parseBoolean);
    if (fallbackToAuthFlow) {
        context.attempted();
        return;
    }

    context.getEvent().error(Errors.UNKNOWN_IDENTITY_PROVIDER);
    context.failure(AuthenticationFlowError.IDENTITY_PROVIDER_NOT_FOUND);
    context.cancelLogin();
    context.resetFlow();
}
 
Example 2
Source File: IdpConfirmLinkAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void actionImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();

    String action = formData.getFirst("submitAction");
    if (action != null && action.equals("updateProfile")) {
        context.resetFlow(() -> {
            AuthenticationSessionModel authSession = context.getAuthenticationSession();

            serializedCtx.saveToAuthenticationSession(authSession, BROKERED_CONTEXT_NOTE);
            authSession.setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        });
    } else if (action != null && action.equals("linkAccount")) {
        context.success();
    } else {
        throw new AuthenticationFlowException("Unknown action: " + action,
                AuthenticationFlowError.INTERNAL_ERROR);
    }
}
 
Example 3
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    if (formData.containsKey("cancel")) {
        context.cancelLogin();
        context.resetFlow();
        return;
    }
    if (!validatePasswordForm(context, formData)) {
        return;
    }

    context.success();
}
 
Example 4
Source File: ThirdPartyMfaAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();

    if (formData.containsKey("cancel")) {
        context.resetFlow();
        context.fork();
        return;
    }

    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();
    String username = user.getUsername();
    log.infof("Request MFA for User. username=%s", username);

    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    MfaMethod mfaMethod = MfaMethod.resolve(authSession.getAuthNote(MFA_METHOD));

    if (formData.containsKey(USE_OTP)) {
        authSession.setAuthNote(MFA_METHOD, MfaMethod.OTP.name());
        requestMfaChallenge(context, username, authSession);
        return;
    }

    String mfaChallengeId = authSession.getAuthNote(MFA_CHALLENGE);
    log.infof("Found challengeId=%s", mfaChallengeId);

    MfaVerifyRequest mfaRequest = new MfaVerifyRequest();
    mfaRequest.setChallengeId(UUID.fromString(mfaChallengeId));
    mfaRequest.setChallengeInput(Sanitizers.BLOCKS.sanitize(formData.getFirst("challenge_input")));

    MfaVerifyResponse mfaVerifyResponse = mfaClient.verifyAuthChallenge(mfaRequest);

    if (mfaVerifyResponse.isSuccessful()) {

        log.infof("MFA authentication successful. realm=%s username=%s mfa_method=%s mfa_challenge_duration=%s", realm.getName(), username, mfaMethod, computeChallengeDuration(authSession));

        signalSuccessfulMfaAuthentication(context, authSession, mfaMethod);
        return;
    }

    if (mfaVerifyResponse.isCompleted()) {
        log.infof("MFA authentication failed. realm=%s username=%s error_code=%s mfa_method=%s mfa_challenge_duration=%s", realm.getName(), user.getUsername(), mfaVerifyResponse.getErrorCode(), mfaMethod, computeChallengeDuration(authSession));
        context.getEvent().user(user);

        String errorMessage = Messages.LOGIN_TIMEOUT;
        if (MfaVerifyResponse.ERR_TIMEOUT.equals(mfaVerifyResponse.getErrorCode())) {
            context.getEvent().error(Errors.SESSION_EXPIRED);
        } else {
            errorMessage = Messages.INVALID_TOTP;
            context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        }
        context.resetFlow();
        context.forkWithErrorMessage(new FormMessage(errorMessage));
        return;
    }

    log.infof("MFA authentication attempt failed. Retrying realm=%s username=%s error_code=%s mfa_method=%s", realm.getName(), user.getUsername(), mfaVerifyResponse.getErrorCode(), mfaMethod);

    Response response = createChallengeFormResponse(context, false, mfaMethod, mfaVerifyResponse);

    context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, response);
}
 
Example 5
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {

    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();

    if (context.getAuthenticationSession().getAuthNote(EXISTING_USER_INFO) != null) {
        context.attempted();
        return;
    }

    String username = getUsername(context, serializedCtx, brokerContext);
    if (username == null) {
        ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username");
        context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        context.resetFlow();
        return;
    }

    ExistingUserInfo duplication = checkExistingUser(context, username, serializedCtx, brokerContext);

    if (duplication == null) {
        logger.debugf("No duplication detected. Creating account for user '%s' and linking with identity provider '%s' .",
                username, brokerContext.getIdpConfig().getAlias());

        UserModel federatedUser = session.users().addUser(realm, username);
        federatedUser.setEnabled(true);
        federatedUser.setEmail(brokerContext.getEmail());
        federatedUser.setFirstName(brokerContext.getFirstName());
        federatedUser.setLastName(brokerContext.getLastName());

        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            federatedUser.setAttribute(attr.getKey(), attr.getValue());
        }

        AuthenticatorConfigModel config = context.getAuthenticatorConfig();
        if (config != null && Boolean.parseBoolean(config.getConfig().get(IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION))) {
            logger.debugf("User '%s' required to update password", federatedUser.getUsername());
            federatedUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
        }

        userRegisteredSuccess(context, federatedUser, serializedCtx, brokerContext);

        context.setUser(federatedUser);
        context.getAuthenticationSession().setAuthNote(BROKER_REGISTERED_NEW_USER, "true");
        context.success();
    } else {
        logger.debugf("Duplication detected. There is already existing user with %s '%s' .",
                duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue());

        // Set duplicated user, so next authenticators can deal with it
        context.getAuthenticationSession().setAuthNote(EXISTING_USER_INFO, duplication.serialize());
        //Only show error message if the authenticator was required
        if (context.getExecution().isRequired()) {
            Response challengeResponse = context.form()
                    .setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .createErrorPage(Response.Status.CONFLICT);
            context.challenge(challengeResponse);
            context.getEvent()
                    .user(duplication.getExistingUserId())
                    .detail("existing_" + duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .removeDetail(Details.AUTH_METHOD)
                    .removeDetail(Details.AUTH_TYPE)
                    .error(Errors.FEDERATED_IDENTITY_EXISTS);
        } else {
            context.attempted();
        }
    }
}