org.keycloak.authentication.AuthenticationFlowError Java Examples

The following examples show how to use org.keycloak.authentication.AuthenticationFlowError. 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: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static RequiredActionProvider createRequiredAction(RequiredActionContextResult context) {
    String display = context.getAuthenticationSession().getAuthNote(OAuth2Constants.DISPLAY);
    if (display == null) return context.getFactory().create(context.getSession());


    if (context.getFactory() instanceof DisplayTypeRequiredActionFactory) {
        RequiredActionProvider provider = ((DisplayTypeRequiredActionFactory)context.getFactory()).createDisplay(context.getSession(), display);
        if (provider != null) return provider;
    }
    // todo create a provider for handling lack of display support
    if (OAuth2Constants.DISPLAY_CONSOLE.equalsIgnoreCase(display)) {
        context.getAuthenticationSession().removeAuthNote(OAuth2Constants.DISPLAY);
        throw new AuthenticationFlowException(AuthenticationFlowError.DISPLAY_NOT_SUPPORTED, ConsoleDisplayMode.browserContinue(context.getSession(), context.getUriInfo().getRequestUri().toString()));

    } else {
        return context.getFactory().create(context.getSession());
    }
}
 
Example #3
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 #4
Source File: IdpUsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected LoginFormsProvider setupForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData, Optional<UserModel> existingUser) {
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    existingUser.ifPresent(u -> formData.putSingle(AuthenticationManager.FORM_USERNAME, u.getUsername()));

    LoginFormsProvider form = context.form()
            .setFormData(formData)
            .setAttribute(LoginFormsProvider.REGISTRATION_DISABLED, true)
            .setInfo(Messages.FEDERATED_IDENTITY_CONFIRM_REAUTHENTICATE_MESSAGE, serializedCtx.getIdentityProviderId());

    SerializedBrokeredIdentityContext serializedCtx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
    if (serializedCtx0 != null) {
        BrokeredIdentityContext ctx0 = serializedCtx0.deserialize(context.getSession(), context.getAuthenticationSession());
        form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, ctx0.getIdpConfig().getAlias(), ctx0.getUsername());
        context.getAuthenticationSession().setAuthNote(AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT, null);
    }

    return form;
}
 
Example #5
Source File: AbstractIdpAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static UserModel getExistingUser(KeycloakSession session, RealmModel realm, AuthenticationSessionModel authSession) {
    String existingUserId = authSession.getAuthNote(EXISTING_USER_INFO);
    if (existingUserId == null) {
        throw new AuthenticationFlowException("Unexpected state. There is no existing duplicated user identified in ClientSession",
                AuthenticationFlowError.INTERNAL_ERROR);
    }

    ExistingUserInfo duplication = ExistingUserInfo.deserialize(existingUserId);

    UserModel existingUser = session.users().getUserById(duplication.getExistingUserId(), realm);
    if (existingUser == null) {
        throw new AuthenticationFlowException("User with ID '" + existingUserId + "' not found.", AuthenticationFlowError.INVALID_USER);
    }

    if (!existingUser.isEnabled()) {
        throw new AuthenticationFlowException("User with ID '" + existingUserId + "', username '" + existingUser.getUsername() + "' disabled.", AuthenticationFlowError.USER_DISABLED);
    }

    return existingUser;
}
 
Example #6
Source File: AbstractIdpAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    AuthenticationSessionModel clientSession = context.getAuthenticationSession();

    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(clientSession, BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }
    BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), clientSession);

    if (!brokerContext.getIdpConfig().isEnabled()) {
        sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    actionImpl(context, serializedCtx, brokerContext);
}
 
Example #7
Source File: AbstractIdpAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }
    BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), authSession);

    if (!brokerContext.getIdpConfig().isEnabled()) {
        sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    authenticateImpl(context, serializedCtx, brokerContext);
}
 
Example #8
Source File: ScriptBasedAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void tryInvoke(String functionName, AuthenticationFlowContext context) {

        if (!hasAuthenticatorConfig(context)) {
            // this is an empty not yet configured script authenticator
            // we mark this execution as success to not lock out users due to incompletely configured authenticators.
            context.success();
            return;
        }

        InvocableScriptAdapter invocableScriptAdapter = getInvocableScriptAdapter(context);

        if (!invocableScriptAdapter.isDefined(functionName)) {
            return;
        }

        try {
            //should context be wrapped in a read-only wrapper?
            invocableScriptAdapter.invokeFunction(functionName, context);
        } catch (ScriptExecutionException e) {
            LOGGER.error(e);
            context.failure(AuthenticationFlowError.INTERNAL_ERROR);
        }
    }
 
Example #9
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 #10
Source File: ConditionalUserAttributeValue.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    boolean result = false;

    // Retrieve configuration
    Map<String, String> config = context.getAuthenticatorConfig().getConfig();
    String attributeName = config.get(ConditionalUserAttributeValueFactory.CONF_ATTRIBUTE_NAME);
    String attributeValue = config.get(ConditionalUserAttributeValueFactory.CONF_ATTRIBUTE_EXPECTED_VALUE);
    boolean negateOutput = Boolean.parseBoolean(config.get(ConditionalUserAttributeValueFactory.CONF_NOT));

    UserModel user = context.getUser();
    if (user == null) {
        throw new AuthenticationFlowException("authenticator: " + ConditionalUserAttributeValueFactory.PROVIDER_ID, AuthenticationFlowError.UNKNOWN_USER);
    }

    List<String> lstValues = user.getAttribute(attributeName);
    if (lstValues != null) {
        result = lstValues.contains(attributeValue);
    }

    if (negateOutput) {
        result = !result;
    }

    return result;
}
 
Example #11
Source File: DummyClientAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    ClientIdAndSecretAuthenticator authenticator = new ClientIdAndSecretAuthenticator();
    authenticator.authenticateClient(context);
    if (context.getStatus().equals(FlowStatus.SUCCESS)) {
        return;
    }

    String clientId = context.getUriInfo().getQueryParameters().getFirst("client_id");

    if (clientId == null) {
        clientId = context.getSession().getAttribute("client_id", String.class);
    }

    ClientModel client = context.getRealm().getClientByClientId(clientId);
    if (client == null) {
        context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
        return;
    }

    context.getEvent().client(client);
    context.setClient(client);
    context.success();
}
 
Example #12
Source File: AbstractIdentityFirstUsernameFormAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected UserModel lookupUser(AuthenticationFlowContext context, String username) {

        try {
            return 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 null;
    }
 
Example #13
Source File: WebAuthn4jAuthenticatorTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
@Test
public void test_action_credential_not_valid() throws Exception {
    // set up mock
    when(session.userCredentialManager()
            .isValid(Mockito.any(RealmModel.class), any(UserModel.class), Mockito.<CredentialInput>anyVararg()))
            .thenThrow(new AuthenticationFlowException("unknown user authenticated by the authenticator", AuthenticationFlowError.UNKNOWN_USER));

    MultivaluedMap<String, String> params = getSimulatedParametersFromAuthenticationResponse();
    when(context.getHttpRequest().getDecodedFormParameters()).thenReturn(params);

    when(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE))
            .thenReturn(getRandomString(32));

    // test
    try {
        authenticator.action(context);
        Assert.fail();
    } catch (AuthenticationFlowException e) {
        // NOP
    }
}
 
Example #14
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 #15
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 #16
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 #17
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 #18
Source File: JWTClientAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected PublicKey getSignatureValidationKey(ClientModel client, ClientAuthenticationFlowContext context, JWSInput jws) {
    PublicKey publicKey = PublicKeyStorageManager.getClientPublicKey(context.getSession(), client, jws);
    if (publicKey == null) {
        Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "unauthorized_client", "Unable to load public key");
        context.failure(AuthenticationFlowError.CLIENT_CREDENTIALS_SETUP_REQUIRED, challengeResponse);
        return null;
    } else {
        return publicKey;
    }
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssertionInvalidSignature() throws Exception {
    // JWT for client1, but signed by privateKey of client2
    String invalidJwt = getClientSignedJWT(getClient2KeyPair(), "client1");

    List<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT));
    parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ASSERTION, invalidJwt));

    CloseableHttpResponse resp = sendRequest(oauth.getServiceAccountUrl(), parameters);
    OAuthClient.AccessTokenResponse response = new OAuthClient.AccessTokenResponse(resp);

    assertError(response, "client1", "unauthorized_client", AuthenticationFlowError.CLIENT_CREDENTIALS_SETUP_REQUIRED.toString().toLowerCase());
}
 
Example #24
Source File: ValidatePassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    String password = retrievePassword(context);
    boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password));
    if (!valid) {
        context.getEvent().user(context.getUser());
        context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }

    context.success();
}
 
Example #25
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void notValidCredentialsAction(final AuthenticationFlowContext context, final RealmModel realm, final UserModel user) {
    context.getEvent().user(user);
    context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
    context.failure(AuthenticationFlowError.INVALID_USER, Response.status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, BASIC_PREFIX + "realm=\"" + realm.getName() + "\"")
            .build());
}
 
Example #26
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void userDisabledAction(AuthenticationFlowContext context, RealmModel realm, UserModel user, String eventError) {
    context.getEvent().user(user);
    context.getEvent().error(eventError);
    context.failure(AuthenticationFlowError.INVALID_USER, Response.status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, BASIC_PREFIX + "realm=\"" + realm.getName() + "\"")
            .build());
}
 
Example #27
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 #28
Source File: PassThroughClientAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    ClientModel client = context.getRealm().getClientByClientId(clientId);
    if (client == null) {
        context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
        return;
    }

    context.getEvent().client(client);
    context.setClient(client);
    context.success();
}
 
Example #29
Source File: UsernameOnlyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    String username = context.getHttpRequest().getDecodedFormParameters().getFirst("username");
    UserModel user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    if (user == null) {
        context.failure(AuthenticationFlowError.UNKNOWN_USER);
        return;
    }
    context.setUser(user);
    context.success();
}
 
Example #30
Source File: PassThroughAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    UserModel user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    if (user == null) {
        context.failure(AuthenticationFlowError.UNKNOWN_USER);
        return;
    }
    context.setUser(user);
    context.success();
}