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

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

    // Note that you can use the `session` to access Keycloaks services.

    Random random = new Random();

    int x = random.nextInt(5);
    int y = random.nextInt(5);

    context.getAuthenticationSession().setAuthNote(EXPECTED_SUM, "" + (x + y));

    Response response = context.form()
            .setAttribute("username", context.getUser().getUsername())
            .setAttribute("x", x)
            .setAttribute("y", y)
            .createForm("simple-form.ftl");

    context.challenge(response);
}
 
Example 2
Source File: ThirdPartyMfaAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
private void requestMfaChallenge(AuthenticationFlowContext context, String username, AuthenticationSessionModel authSession) {

        MfaChallengeRequest mfaRequest = createMfaChallengeRequest(username, authSession);
        MfaChallengeResponse mfaResponse = mfaClient.requestAuthChallenge(mfaRequest);

        MfaMethod mfaMethod = mfaRequest.getMfaMethod();
        if (mfaResponse.isCompleted()) {
            log.infof("MFA Challenge immediately completed. username=%s challengeId=%s mfa_method=%s mfa_challenge_duration=%s", username, mfaResponse.getChallengeId(), mfaMethod, computeChallengeDuration(authSession));

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

        if (mfaResponse.isSubmitted()) {
            log.infof("Retrieved challengeId=%s", mfaResponse.getChallengeId());
            authSession.setAuthNote(MFA_CHALLENGE, mfaResponse.getChallengeId().toString());
            authSession.setAuthNote(MFA_CHALLENGE_START, String.valueOf(System.currentTimeMillis()));

            Response response = createChallengeFormResponse(context, true, mfaRequest.getMfaMethod(), mfaResponse);
            context.challenge(response);
            return;
        }

        log.warnf("MFA Challenge request failed. username=%s challengeId=%s mfa_error=%s", username, mfaResponse.getChallengeId(), mfaResponse.getErrorCode());
        context.forkWithErrorMessage(new FormMessage(Messages.FAILED_TO_PROCESS_RESPONSE));
    }
 
Example 3
Source File: IdpConfirmLinkAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source File: IdpReviewProfileAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
    IdentityProviderModel idpConfig = brokerContext.getIdpConfig();

    if (requiresUpdateProfilePage(context, userCtx, brokerContext)) {

        logger.debugf("Identity provider '%s' requires update profile action for broker user '%s'.", idpConfig.getAlias(), userCtx.getUsername());

        // No formData for first render. The profile is rendered from userCtx
        Response challengeResponse = context.form()
                .setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
                .setFormData(null)
                .createUpdateProfilePage();
        context.challenge(challengeResponse);
    } else {
        // Not required to update profile. Marked success
        context.success();
    }
}
 
Example 5
Source File: WebAuthn4jAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
    Map<String, String> params = generateParameters(context.getRealm(), context.getUriInfo().getBaseUri());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, params.get(WebAuthnConstants.CHALLENGE));
    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already identified
        isUserIdentified = true;
        form.setAttribute("authenticators", new WebAuthnAuthenticatorsBean(user));
    } else {
        // in ID-less & Password-less Scenario
        // NOP
    }
    params.put("isUserIdentified", Boolean.toString(isUserIdentified));
    params.forEach(form::setAttribute);
    context.challenge(form.createForm("webauthn.ftl"));
}
 
Example 6
Source File: UsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> formData = new MultivaluedMapImpl<>();
    String loginHint = context.getAuthenticationSession().getClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM);

    String rememberMeUsername = AuthenticationManager.getRememberMeUsername(context.getRealm(), context.getHttpRequest().getHttpHeaders());

    if (loginHint != null || rememberMeUsername != null) {
        if (loginHint != null) {
            formData.add(AuthenticationManager.FORM_USERNAME, loginHint);
        } else {
            formData.add(AuthenticationManager.FORM_USERNAME, rememberMeUsername);
            formData.add("rememberMe", "on");
        }
    }
    Response challengeResponse = challenge(context, formData);
    context.challenge(challengeResponse);
}
 
Example 7
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
 
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);
    form.setAttribute(WebAuthnConstants.CHALLENGE, challengeValue);

    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = getRpID(context);
    form.setAttribute(WebAuthnConstants.RP_ID, rpId);

    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already been identified
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators().isEmpty()) {
            // require the user to register webauthn authenticator
            return;
        }
        isUserIdentified = true;
        form.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
    } else {
        // in ID-less & Password-less Scenario
        // NOP
    }
    form.setAttribute(WebAuthnConstants.IS_USER_IDENTIFIED, Boolean.toString(isUserIdentified));

    // read options from policy
    String userVerificationRequirement = policy.getUserVerificationRequirement();
    form.setAttribute(WebAuthnConstants.USER_VERIFICATION, userVerificationRequirement);

    context.challenge(form.createLoginWebAuthn());
}
 
Example 8
Source File: NoCookieFlowRedirectAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    HttpRequest httpRequest = context.getHttpRequest();

    // only do redirects for GET requests
    if (HttpMethod.GET.equalsIgnoreCase(httpRequest.getHttpMethod())) {
        KeycloakUriInfo uriInfo = context.getSession().getContext().getUri();
        if (!uriInfo.getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
            Response response = Response.status(302).header(HttpHeaders.LOCATION, context.getRefreshUrl(true)).build();
            context.challenge(response);
            return;
        }
    }

    context.success();
}
 
Example 9
Source File: CliUsernamePasswordAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    String header = getHeader(context);
    Response response  = context.form()
            .setStatus(Response.Status.UNAUTHORIZED)
            .setMediaType(MediaType.TEXT_PLAIN_TYPE)
            .setResponseHeader(HttpHeaders.WWW_AUTHENTICATE, header)
            .createForm("cli_splash.ftl");
    context.challenge(response);


}
 
Example 10
Source File: PushButtonAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
    public void authenticate(AuthenticationFlowContext context) {
        String accessCode = context.generateAccessCode();
        String actionUrl = context.getActionUrl(accessCode).toString();

        StringBuilder response = new StringBuilder("<html><head><title>PushTheButton</title></head><body>");

        UserModel user = context.getUser();
        if (user == null) {
            response.append("No authenticated user<br>");
        } else {
            response.append("Authenticated user: " + user.getUsername() + "<br>");
        }

        response.append("<form method='POST' action='" + actionUrl + "'>");
        response.append(" This is the Test Approver. Press login to continue.<br>");
        response.append(" <input type='submit' name='submit1' value='Submit' />");
        response.append("</form></body></html>");
        String html = response.toString();

        Response jaxrsResponse = Response
                .status(Response.Status.OK)
                .type("text/html")
                .entity(html)
                .build();

        context.challenge(jaxrsResponse);

//        Response challenge = context.form().createForm("login-approve.ftl");
//        context.challenge(challenge);
    }
 
Example 11
Source File: SecretQuestionAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    if (hasCookie(context)) {
        context.success();
        return;
    }
    Response challenge = context.form()
            .createForm("secret-question.ftl");
    context.challenge(challenge);
}
 
Example 12
Source File: TenantSelectorAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    // Note that you can use the `session` to access Keycloaks services.

    Response response = context.form()
            .setAttribute("username", context.getUser().getUsername())
            .createForm("tenant-select-form.ftl");

    context.challenge(response);
}
 
Example 13
Source File: OTPFormAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    Response challengeResponse = challenge(context, null);
    context.challenge(challengeResponse);
}
 
Example 14
Source File: ClickThroughAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    Response challenge = context.form().createForm("terms.ftl");
    context.challenge(challenge);
}
 
Example 15
Source File: PasswordForm.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    Response challengeResponse = context.form().createLoginPassword();
    context.challenge(challengeResponse);
}
 
Example 16
Source File: ConsoleOTPFormAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    Response challengeResponse = challenge(context, null);
    context.challenge(challengeResponse);
}
 
Example 17
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();
        }
    }
}
 
Example 18
Source File: IdpReviewProfileAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void actionImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
    EventBuilder event = context.getEvent();
    event.event(EventType.UPDATE_PROFILE);
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();

    RealmModel realm = context.getRealm();

    List<FormMessage> errors = Validation.validateUpdateProfileForm(realm, formData, userCtx.isEditUsernameAllowed());
    if (errors != null && !errors.isEmpty()) {
        Response challenge = context.form()
                .setErrors(errors)
                .setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
                .setFormData(formData)
                .createUpdateProfilePage();
        context.challenge(challenge);
        return;
    }

    String username = realm.isRegistrationEmailAsUsername() ? formData.getFirst(UserModel.EMAIL) : formData.getFirst(UserModel.USERNAME);
    userCtx.setUsername(username);
    userCtx.setFirstName(formData.getFirst(UserModel.FIRST_NAME));
    userCtx.setLastName(formData.getFirst(UserModel.LAST_NAME));

    String email = formData.getFirst(UserModel.EMAIL);
    if (!ObjectUtil.isEqualOrBothNull(email, userCtx.getEmail())) {
        if (logger.isTraceEnabled()) {
            logger.tracef("Email updated on updateProfile page to '%s' ", email);
        }

        userCtx.setEmail(email);
        context.getAuthenticationSession().setAuthNote(UPDATE_PROFILE_EMAIL_CHANGED, "true");
    }

    AttributeFormDataProcessor.process(formData, realm, userCtx);

    userCtx.saveToAuthenticationSession(context.getAuthenticationSession(), BROKERED_CONTEXT_NOTE);

    logger.debugf("Profile updated successfully after first authentication with identity provider '%s' for broker user '%s'.", brokerContext.getIdpConfig().getAlias(), userCtx.getUsername());

    event.detail(Details.UPDATED_EMAIL, email);

    // Ensure page is always shown when user later returns to it - for example with form "back" button
    context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");

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

    Response response = challenge(context, null);

    context.challenge(response);
}
 
Example 20
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 3 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    Response response = challenge(context, null);

    context.challenge(response);
}