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

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext#failureChallenge() . 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: BasicAuthOTPAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean checkOtp(AuthenticationFlowContext context, String otp) {
    OTPCredentialModel preferredCredential = getCredentialProvider(context.getSession())
            .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser());
    boolean valid = getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(),
            new UserCredentialModel(preferredCredential.getId(), getCredentialProvider(context.getSession()).getType(), otp));

    if (!valid) {
        context.getEvent().user(context.getUser()).error(Errors.INVALID_USER_CREDENTIALS);
        if (context.getExecution().isRequired()){
            Response challengeResponse = challenge(context, Messages.INVALID_TOTP);
            context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse);
        } else {
            context.attempted();
        }
        return false;
    }

    return true;
}
 
Example 2
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private void failWithInvalidCredentials(AuthenticationFlowContext context, UserModel user) {
    context.getEvent().user(user);
    context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
    Response challengeResponse = challenge(context, Messages.INVALID_USER);
    context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse);
    context.clearUser();
}
 
Example 3
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 5 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    logger.debug("action called ... context = " + context);
    CODE_STATUS status = validateCode(context);
    Response challenge = null;
    switch (status) {
        case EXPIRED:
            challenge =  context.form()
                    .setError("code is expired")
                    .createForm("sms-validation.ftl");
            context.failureChallenge(AuthenticationFlowError.EXPIRED_CODE, challenge);
            break;

        case INVALID:
            if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.OPTIONAL ||
                    context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.ALTERNATIVE) {
                logger.debug("Calling context.attempted()");
                context.attempted();
            } else if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.REQUIRED) {
                challenge =  context.form()
                        .setError("badCode")
                        .createForm("sms-validation.ftl");
                context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge);
            } else {
                // Something strange happened
                logger.warn("Undefined execution ...");
            }
            break;

        case VALID:
            context.success();
            break;

    }
}
 
Example 4
Source File: SecretQuestionAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    boolean validated = validateAnswer(context);
    if (!validated) {
        Response challenge =  context.form()
                .setError("badSecret")
                .createForm("secret-question.ftl");
        context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge);
        return;
    }
    setCookie(context);
    context.success();
}
 
Example 5
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Response setDuplicateUserChallenge(AuthenticationFlowContext context, String eventError, String loginFormError, AuthenticationFlowError authenticatorError) {
    context.getEvent().error(eventError);
    Response challengeResponse = context.form()
            .setError(loginFormError).createLoginUsernamePassword();
    context.failureChallenge(authenticatorError, challengeResponse);
    return challengeResponse;
}
 
Example 6
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void testInvalidUser(AuthenticationFlowContext context, UserModel user) {
    if (user == null) {
        dummyHash(context);
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = challenge(context, getDefaultChallengeMessage(context));
        context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
    }
}
 
Example 7
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserModel getUser(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) {
    String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
    if (username == null) {
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = challenge(context, getDefaultChallengeMessage(context));
        context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return null;
    }

    // remove leading and trailing whitespace
    username = username.trim();

    context.getEvent().detail(Details.USERNAME, username);
    context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

    UserModel user = null;
    try {
        user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    } catch (ModelDuplicateException mde) {
        ServicesLogger.LOGGER.modelDuplicateException(mde);

        // Could happen during federation import
        if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
            setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER);
        } else {
            setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER);
        }
        return user;
    }

    testInvalidUser(context, user);
    return user;
}
 
Example 8
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean badPasswordHandler(AuthenticationFlowContext context, UserModel user, boolean clearUser,boolean isEmptyPassword) {
    context.getEvent().user(user);
    context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
    Response challengeResponse = challenge(context, getDefaultChallengeMessage(context));
    if(isEmptyPassword) {
        context.forceChallenge(challengeResponse);
    }else{
        context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse);
    }

    if (clearUser) {
        context.clearUser();
    }
    return false;
}
 
Example 9
Source File: AbstractIdpAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void sendFailureChallenge(AuthenticationFlowContext context, Response.Status status, String eventError, String errorMessage, AuthenticationFlowError flowError) {
    context.getEvent().user(context.getUser())
            .error(eventError);
    Response challengeResponse = context.form()
            .setError(errorMessage)
            .createErrorPage(status);
    context.failureChallenge(flowError, challengeResponse);
}
 
Example 10
Source File: CliUsernamePasswordAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected Response setDuplicateUserChallenge(AuthenticationFlowContext context, String eventError, String loginFormError, AuthenticationFlowError authenticatorError) {
    context.getEvent().error(eventError);
    String header = getHeader(context);
    Response challengeResponse  = Response.status(401)
            .type(MediaType.TEXT_PLAIN_TYPE)
            .header(HttpHeaders.WWW_AUTHENTICATE, header)
            .entity("\n" + context.form().getMessage(loginFormError) + "\n")
            .build();

    context.failureChallenge(authenticatorError, challengeResponse);
    return challengeResponse;
}
 
Example 11
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 12
Source File: AbstractIdentityFirstUsernameFormAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
protected void failWithUserNotFound(AuthenticationFlowContext context) {
    context.getEvent().error(Errors.USER_NOT_FOUND);
    Response challengeResponse = challenge(context, Messages.INVALID_USER);
    context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
}