org.keycloak.forms.login.LoginFormsProvider Java Examples

The following examples show how to use org.keycloak.forms.login.LoginFormsProvider. 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: AuthenticationProcessor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public LoginFormsProvider form() {
    String accessCode = generateAccessCode();
    URI action = getActionUrl(accessCode);
    LoginFormsProvider provider = getSession().getProvider(LoginFormsProvider.class)
            .setAuthContext(this)
            .setAuthenticationSession(getAuthenticationSession())
            .setUser(getUser())
            .setActionUri(action)
            .setExecution(getExecution().getId())
            .setFormData(request.getHttpMethod().equalsIgnoreCase("post") ? request.getDecodedFormParameters() :
                    new MultivaluedHashMap<>())
            .setClientSessionCode(accessCode);
    if (getForwardedErrorMessage() != null) {
        provider.addError(getForwardedErrorMessage());
    } else if (getForwardedSuccessMessage() != null) {
        provider.addSuccess(getForwardedSuccessMessage());
    }
    return provider;
}
 
Example #2
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 #3
Source File: FormAuthenticationFlow.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public Response renderForm(MultivaluedMap<String, String> formData, List<FormMessage> errors) {
    String executionId = formExecution.getId();
    processor.getAuthenticationSession().setAuthNote(AuthenticationProcessor.CURRENT_AUTHENTICATION_EXECUTION, executionId);
    String code = processor.generateCode();
    URI actionUrl = getActionUrl(executionId, code);
    LoginFormsProvider form = processor.getSession().getProvider(LoginFormsProvider.class)
            .setAuthenticationSession(processor.getAuthenticationSession())
            .setActionUri(actionUrl)
            .setExecution(executionId)
            .setClientSessionCode(code)
            .setFormData(formData)
            .setErrors(errors);
    for (AuthenticationExecutionModel formActionExecution : formActionExecutions) {
        if (!formActionExecution.isEnabled()) continue;
        FormAction action = processor.getSession().getProvider(FormAction.class, formActionExecution.getAuthenticator());
        FormContext result = new FormContextImpl(formActionExecution);
        action.buildPage(result, form);
    }
    FormContext context = new FormContextImpl(formExecution);
    return formAuthenticator.render(context, form);
}
 
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: 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 #6
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 #7
Source File: RegistrationRecaptcha.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void buildPage(FormContext context, LoginFormsProvider form) {
    AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
    String userLanguageTag = context.getSession().getContext().resolveLocale(context.getUser()).toLanguageTag();
    if (captchaConfig == null || captchaConfig.getConfig() == null
            || captchaConfig.getConfig().get(SITE_KEY) == null
            || captchaConfig.getConfig().get(SITE_SECRET) == null
            ) {
        form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED));
        return;
    }
    String siteKey = captchaConfig.getConfig().get(SITE_KEY);
    form.setAttribute("recaptchaRequired", true);
    form.setAttribute("recaptchaSiteKey", siteKey);
    form.addScript("https://www." + getRecaptchaDomain(captchaConfig) + "/recaptcha/api.js?hl=" + userLanguageTag);
}
 
Example #8
Source File: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #9
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
	context.getEvent().detail(Details.AUTH_METHOD, "auth_method");
	if (logger.isInfoEnabled()) {
		logger.info(
				"validateRecaptcha(AuthenticationFlowContext, boolean, String, String) - Before the validation");
	}

	AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig();
	LoginFormsProvider form = context.form();
	String userLanguageTag = context.getSession().getContext().resolveLocale(context.getUser()).toLanguageTag();

	if (captchaConfig == null || captchaConfig.getConfig() == null
			|| captchaConfig.getConfig().get(SITE_KEY) == null
			|| captchaConfig.getConfig().get(SITE_SECRET) == null) {
		form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED));
		return;
	}
	siteKey = captchaConfig.getConfig().get(SITE_KEY);
	form.setAttribute("recaptchaRequired", true);
	form.setAttribute("recaptchaSiteKey", siteKey);
	form.addScript("https://www.google.com/recaptcha/api.js?hl=" + userLanguageTag);

	super.authenticate(context);
}
 
Example #10
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 #11
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
private LoginFormsProvider createSelectUserForm(AuthenticationFlowContext context, String error) {

        MultivaluedMap<String, String> formData = createLoginFormData(context);

        LoginFormsProvider form = context.form();
        if (formData.size() > 0) {
            form.setFormData(formData);
        }
        form.setAttribute("login", new LoginBean(formData));

        if (error != null) {
            form.setError(error);
        }

        return form;
    }
 
Example #12
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, String error) {

    String useAjax = getConfigProperty(context, USE_AXJAX_CONFIG_PROPERTY, "true");
    String loginHint = context.getHttpRequest().getUri().getQueryParameters().getFirst(OIDCLoginProtocol.LOGIN_HINT_PARAM);

    LoginFormsProvider usernameLoginForm = createSelectUserForm(context, error)
            .setAttribute("useAjax", "true".equals(useAjax));

    if (loginHint != null) {
        MultivaluedHashMap<String, String> formData = new MultivaluedHashMap<>();
        formData.add(AuthenticationManager.FORM_USERNAME, loginHint);
        usernameLoginForm.setAttribute("login", new LoginBean(formData));
    }

    return usernameLoginForm
            .createForm("select-user-form.ftl");
}
 
Example #13
Source File: LoginFormsUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static List<IdentityProviderModel> filterIdentityProvidersByUser(List<IdentityProviderModel> providers, KeycloakSession session, RealmModel realm,
                                                                  Map<String, Object> attributes, MultivaluedMap<String, String> formData) {

    Boolean usernameEditDisabled = (Boolean) attributes.get(LoginFormsProvider.USERNAME_EDIT_DISABLED);
    if (usernameEditDisabled != null && usernameEditDisabled) {
        String username = formData.getFirst(UserModel.USERNAME);
        if (username == null) {
            throw new IllegalStateException("USERNAME_EDIT_DISABLED but username not known");
        }

        UserModel user = session.users().getUserByUsername(username, realm);
        if (user == null || !user.isEnabled()) {
            throw new IllegalStateException("User " + username + " not found or disabled");
        }

        Set<FederatedIdentityModel> fedLinks = session.users().getFederatedIdentities(user, realm);
        Set<String> federatedIdentities = new HashSet<>();
        for (FederatedIdentityModel fedLink : fedLinks) {
            federatedIdentities.add(fedLink.getIdentityProvider());
        }

        List<IdentityProviderModel> result = new LinkedList<>();
        for (IdentityProviderModel idp : providers) {
            if (federatedIdentities.contains(idp.getAlias())) {
                result.add(idp);
            }
        }
        return result;
    } else {
        return providers;
    }
}
 
Example #14
Source File: IdpEmailVerificationAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void showEmailSentPage(AuthenticationFlowContext context, BrokeredIdentityContext brokerContext) {
    String accessCode = context.generateAccessCode();
    URI action = context.getActionUrl(accessCode);

    Response challenge = context.form()
            .setStatus(Response.Status.OK)
            .setAttribute(LoginFormsProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext)
            .setActionUri(action)
            .setExecution(context.getExecution().getId())
            .createIdpLinkEmailPage();
    context.forceChallenge(challenge);
}
 
Example #15
Source File: ConsoleDisplayMode.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Browser is required to continue login.  This will prompt client on whether to continue with a browser or abort.
 *
 * @param session
 * @param callback
 * @return
 */
public static Response browserContinue(KeycloakSession session, String callback) {
    String browserContinueMsg = session.getProvider(LoginFormsProvider.class).getMessage("browserContinue");
    String browserPrompt = session.getProvider(LoginFormsProvider.class).getMessage("browserContinuePrompt");
    String answer = session.getProvider(LoginFormsProvider.class).getMessage("browserContinueAnswer");

    String header = "X-Text-Form-Challenge callback=\"" + callback + "\"";
    header += " browserContinue=\"" + browserPrompt + "\" answer=\"" + answer + "\"";
    return Response.status(Response.Status.UNAUTHORIZED)
            .header("WWW-Authenticate", header)
            .type(MediaType.TEXT_PLAIN)
            .entity("\n" + browserContinueMsg + "\n").build();
}
 
Example #16
Source File: FreeMarkerLoginFormsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public LoginFormsProvider addSuccess(FormMessage errorMessage) {
    if (this.messageType != MessageType.SUCCESS) {
        this.messageType = null;
        this.messages = null;
    }
    if (messages == null) {
        this.messageType = MessageType.SUCCESS;
        this.messages = new LinkedList<>();
    }
    this.messages.add(errorMessage);
    return this;

}
 
Example #17
Source File: VerifyEmail.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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;
    }

    LoginFormsProvider loginFormsProvider = context.form();
    Response challenge;

    // Do not allow resending e-mail by simple page refresh, i.e. when e-mail sent, it should be resent properly via email-verification endpoint
    if (! Objects.equals(authSession.getAuthNote(Constants.VERIFY_EMAIL_KEY), email)) {
        authSession.setAuthNote(Constants.VERIFY_EMAIL_KEY, email);
        EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, email);
        challenge = sendVerifyEmail(context.getSession(), loginFormsProvider, context.getUser(), context.getAuthenticationSession(), event);
    } else {
        challenge = loginFormsProvider.createResponse(UserModel.RequiredAction.VERIFY_EMAIL);
    }

    context.challenge(challenge);
}
 
Example #18
Source File: VerifyEmail.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response sendVerifyEmail(KeycloakSession session, LoginFormsProvider forms, UserModel user, AuthenticationSessionModel authSession, EventBuilder event) throws UriBuilderException, IllegalArgumentException {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();

    int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(VerifyEmailActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;

    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
    VerifyEmailActionToken token = new VerifyEmailActionToken(user.getId(), absoluteExpirationInSecs, authSessionEncodedId, user.getEmail(), authSession.getClient().getClientId());
    UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
            authSession.getClient().getClientId(), authSession.getTabId());
    String link = builder.build(realm.getName()).toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);

    try {
        session
          .getProvider(EmailTemplateProvider.class)
          .setAuthenticationSession(authSession)
          .setRealm(realm)
          .setUser(user)
          .sendVerifyEmail(link, expirationInMinutes);
        event.success();
    } catch (EmailException e) {
        logger.error("Failed to send verification email", e);
        event.error(Errors.EMAIL_SEND_FAILED);
    }

    return forms.createResponse(UserModel.RequiredAction.VERIFY_EMAIL);
}
 
Example #19
Source File: ExecuteActionsActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Response handleToken(ExecuteActionsActionToken token, ActionTokenContext<ExecuteActionsActionToken> tokenContext) {
    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        // Update the authentication session in the token
        String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
        token.setCompoundAuthenticationSessionId(authSessionEncodedId);
        UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
                authSession.getClient().getClientId(), authSession.getTabId());
        String confirmUri = builder.build(realm.getName()).toString();

        return session.getProvider(LoginFormsProvider.class)
                .setAuthenticationSession(authSession)
                .setSuccess(Messages.CONFIRM_EXECUTION_OF_ACTIONS)
                .setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri)
                .setAttribute(Constants.TEMPLATE_ATTR_REQUIRED_ACTIONS, token.getRequiredActions())
                .createInfoPage();
    }

    String redirectUri = RedirectUtils.verifyRedirectUri(tokenContext.getSession(), token.getRedirectUri(), authSession.getClient());

    if (redirectUri != null) {
        authSession.setAuthNote(AuthenticationManager.SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS, "true");

        authSession.setRedirectUri(redirectUri);
        authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
    }

    token.getRequiredActions().stream().forEach(authSession::addRequiredAction);

    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    // verify user email as we know it is valid as this entry point would never have gotten here.
    user.setEmailVerified(true);

    String nextAction = AuthenticationManager.nextRequiredAction(tokenContext.getSession(), authSession, tokenContext.getClientConnection(), tokenContext.getRequest(), tokenContext.getUriInfo(), tokenContext.getEvent());
    return AuthenticationManager.redirectToRequiredActions(tokenContext.getSession(), tokenContext.getRealm(), authSession, tokenContext.getUriInfo(), nextAction);
}
 
Example #20
Source File: ConsoleDisplayMode.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Create a theme form pre-populated with challenge
 *
 * @return
 */
public LoginFormsProvider form() {
    if (header == null) throw new RuntimeException("Header Not Set");
    return formInternal()
            .setStatus(Response.Status.UNAUTHORIZED)
            .setMediaType(MediaType.TEXT_PLAIN_TYPE)
            .setResponseHeader(HttpHeaders.WWW_AUTHENTICATE, header.build());
}
 
Example #21
Source File: X509ClientCertificateAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response createResponse(AuthenticationFlowContext context,
                                     String subjectDN,
                                     boolean isUserEnabled,
                                     String errorMessage,
                                     Object[] errorParameters) {

    LoginFormsProvider form = context.form();
    if (errorMessage != null && errorMessage.trim().length() > 0) {
        List<FormMessage> errors = new LinkedList<>();

        errors.add(new FormMessage(errorMessage));
        if (errorParameters != null) {

            for (Object errorParameter : errorParameters) {
                if (errorParameter == null) continue;
                for (String part : errorParameter.toString().split("\n")) {
                    errors.add(new FormMessage(part));
                }
            }
        }
        form.setErrors(errors);
    }

    MultivaluedMap<String,String> formData = new MultivaluedHashMap<>();
    formData.add("username", context.getUser() != null ? context.getUser().getUsername() : "unknown user");
    formData.add("subjectDN", subjectDN);
    formData.add("isUserEnabled", String.valueOf(isUserEnabled));

    form.setFormData(formData);

    return form.createX509ConfirmPage();
}
 
Example #22
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response createErrorResponse(AuthenticationFlowContext context, final String errorCase) {
    LoginFormsProvider provider = context.form().setError(errorCase);
    UserModel user = context.getUser();
    if (user != null) {
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators() != null) {
            provider.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
        }
    }
    return provider.createWebAuthnErrorPage();
}
 
Example #23
Source File: SpnegoAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response challengeNegotiation(AuthenticationFlowContext context, final String negotiateToken) {
    String negotiateHeader = negotiateToken == null ? KerberosConstants.NEGOTIATE : KerberosConstants.NEGOTIATE + " " + negotiateToken;

    if (logger.isTraceEnabled()) {
        logger.trace("Sending back " + HttpHeaders.WWW_AUTHENTICATE + ": " + negotiateHeader);
    }
    if (context.getExecution().isRequired()) {
        return context.getSession().getProvider(LoginFormsProvider.class)
                .setAuthenticationSession(context.getAuthenticationSession())
                .setResponseHeader(HttpHeaders.WWW_AUTHENTICATE, negotiateHeader)
                .setError(Messages.KERBEROS_NOT_ENABLED).createErrorPage(Response.Status.UNAUTHORIZED);
    } else {
        return optionalChallengeRedirect(context, negotiateHeader);
    }
}
 
Example #24
Source File: UsernameForm.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, MultivaluedMap<String, String> formData) {
    LoginFormsProvider forms = context.form();

    if (!formData.isEmpty()) forms.setFormData(formData);

    return forms.createLoginUsername();
}
 
Example #25
Source File: AuthenticationFlowURLHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Response showPageExpired(AuthenticationSessionModel authSession) {
    URI lastStepUrl = getLastExecutionUrl(authSession);

    logger.debugf("Redirecting to 'page expired' now. Will use last step URL: %s", lastStepUrl);

    return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession)
            .setActionUri(lastStepUrl)
            .setExecution(getExecutionId(authSession))
            .createLoginExpiredPage();
}
 
Example #26
Source File: RequiredActionContextResult.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public LoginFormsProvider form() {
    String accessCode = generateCode();
    URI action = getActionUrl(accessCode);
    LoginFormsProvider provider = getSession().getProvider(LoginFormsProvider.class)
            .setAuthenticationSession(getAuthenticationSession())
            .setUser(getUser())
            .setActionUri(action)
            .setExecution(getExecution())
            .setClientSessionCode(accessCode);
    return provider;
}
 
Example #27
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Response handleBrowserExceptionList(AuthenticationFlowException e) {
    LoginFormsProvider forms = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authenticationSession);
    ServicesLogger.LOGGER.failedAuthentication(e);
    forms.addError(new FormMessage(Messages.UNEXPECTED_ERROR_HANDLING_REQUEST));
    for (AuthenticationFlowException afe : e.getAfeList()) {
        ServicesLogger.LOGGER.failedAuthentication(afe);
        switch (afe.getError()){
            case INVALID_USER:
                event.error(Errors.USER_NOT_FOUND);
                forms.addError(new FormMessage(Messages.INVALID_USER));
                break;
            case USER_DISABLED:
                event.error(Errors.USER_DISABLED);
                forms.addError(new FormMessage(Messages.ACCOUNT_DISABLED));
                break;
            case USER_TEMPORARILY_DISABLED:
                event.error(Errors.USER_TEMPORARILY_DISABLED);
                forms.addError(new FormMessage(Messages.INVALID_USER));
                break;
            case INVALID_CLIENT_SESSION:
                event.error(Errors.INVALID_CODE);
                forms.addError(new FormMessage(Messages.INVALID_CODE));
                break;
            case EXPIRED_CODE:
                event.error(Errors.EXPIRED_CODE);
                forms.addError(new FormMessage(Messages.EXPIRED_CODE));
                break;
            case DISPLAY_NOT_SUPPORTED:
                event.error(Errors.DISPLAY_UNSUPPORTED);
                forms.addError(new FormMessage(Messages.DISPLAY_UNSUPPORTED));
                break;
            case CREDENTIAL_SETUP_REQUIRED:
                event.error(Errors.INVALID_USER_CREDENTIALS);
                forms.addError(new FormMessage(Messages.CREDENTIAL_SETUP_REQUIRED));
                break;
        }
    }
    return forms.createErrorPage(Response.Status.BAD_REQUEST);
}
 
Example #28
Source File: AccountFormService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response forwardToPage(String path, AccountPages page) {
    if (auth != null) {
        try {
            auth.require(AccountRoles.MANAGE_ACCOUNT);
        } catch (ForbiddenException e) {
            return session.getProvider(LoginFormsProvider.class).setError(Messages.NO_ACCESS).createErrorPage(Response.Status.FORBIDDEN);
        }

        setReferrerOnPage();

        UserSessionModel userSession = auth.getSession();

        String tabId = session.getContext().getUri().getQueryParameters().getFirst(org.keycloak.models.Constants.TAB_ID);
        if (tabId != null) {
            AuthenticationSessionModel authSession = new AuthenticationSessionManager(session).getAuthenticationSessionByIdAndClient(realm, userSession.getId(), client, tabId);
            if (authSession != null) {
                String forwardedError = authSession.getAuthNote(ACCOUNT_MGMT_FORWARDED_ERROR_NOTE);
                if (forwardedError != null) {
                    try {
                        FormMessage errorMessage = JsonSerialization.readValue(forwardedError, FormMessage.class);
                        account.setError(Response.Status.INTERNAL_SERVER_ERROR, errorMessage.getMessage(), errorMessage.getParameters());
                        authSession.removeAuthNote(ACCOUNT_MGMT_FORWARDED_ERROR_NOTE);
                    } catch (IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                }
            }
        }

        String locale = session.getContext().getUri().getQueryParameters().getFirst(LocaleSelectorProvider.KC_LOCALE_PARAM);
        if (locale != null) {
            LocaleUpdaterProvider updater = session.getProvider(LocaleUpdaterProvider.class);
            updater.updateUsersLocale(auth.getUser(), locale);
        }

        return account.createResponse(page);
    } else {
        return login(path);
    }
}
 
Example #29
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #30
Source File: ThirdPartyMfaAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Response createChallengeFormResponse(AuthenticationFlowContext context, boolean firstTry, MfaMethod mfaMethod, MfaResponse mfaResponse) {

        LoginFormsProvider form = context.form()
                .setAttribute(MFA_METHOD, mfaMethod.name())
                .setAttribute("mfa_error", mfaResponse.getErrorCode());

        if (MfaMethod.PUSH.equals(mfaMethod)) {
            form.setAttribute("hint", firstTry ? "mfa_push_await_challenge_response" : "mfa_push_await_challenge_response");
        }

        Locale locale = session.getContext().resolveLocale(context.getUser());
        form.setAttribute("customMsg", new MessageFormatterMethod(locale, MfaMessages.getMessages()));

        if (mfaResponse.getErrorCode() != null) {
            if (MfaVerifyResponse.ERR_INVALID_CODE.equals(mfaResponse.getErrorCode())) {
                form.setError(Messages.INVALID_TOTP);
            } else {
                form.setError(mfaResponse.getErrorCode());
            }
        }

        switch (mfaMethod) {
            case OTP:
                return form.createForm("custom-mfa-form-otp.ftl");

            case PUSH:
            default:
                return form.createForm("custom-mfa-form-push.ftl");
        }

    }