Java Code Examples for org.keycloak.forms.login.LoginFormsProvider#setAttribute()

The following examples show how to use org.keycloak.forms.login.LoginFormsProvider#setAttribute() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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");
        }

    }
 
Example 9
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, String error) {

    LoginFormsProvider form = context.form();

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

    String attemptedUsername = context.getAuthenticationSession().getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    form.setAttribute(AuthenticationManager.FORM_USERNAME, attemptedUsername);

    Response response = form.createForm("validate-password-form.ftl");
    return response;
}
 
Example 10
Source File: CASLoginProtocol.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
@Override
public Response finishLogout(UserSessionModel userSession) {
    String redirectUri = userSession.getNote(CASLoginProtocol.LOGOUT_REDIRECT_URI);

    event.event(EventType.LOGOUT);
    event.user(userSession.getUser()).session(userSession).success();

    if (redirectUri != null) {
        return Response.status(302).location(URI.create(redirectUri)).build();
    } else {
        LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setSuccess("Logout successful");
        infoPage.setAttribute("skipLink", true);
        return infoPage.createInfoPage();
    }
}
 
Example 11
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 12
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 13
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 4 votes vote down vote up
@Override
protected Response createLoginForm( LoginFormsProvider form ) {
	form.setAttribute("recaptchaRequired", true);
	form.setAttribute("recaptchaSiteKey", siteKey);
	return super.createLoginForm( form );
}
 
Example 14
Source File: RegistrationPassword.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void buildPage(FormContext context, LoginFormsProvider form) {
    form.setAttribute("passwordRequired", true);
}
 
Example 15
Source File: SessionCodeChecks.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthenticationSessionModel initialVerifyAuthSession() {
    // Basic realm checks
    if (!checkSsl()) {
        event.error(Errors.SSL_REQUIRED);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
        return null;
    }
    if (!realm.isEnabled()) {
        event.error(Errors.REALM_DISABLED);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
        return null;
    }

    // Setup client to be shown on error/info page based on "client_id" parameter
    logger.debugf("Will use client '%s' in back-to-application link", clientId);
    ClientModel client = null;
    if (clientId != null) {
        client = realm.getClientByClientId(clientId);
    }
    if (client != null) {
        session.getContext().setClient(client);
    }


    // object retrieve
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);
    AuthenticationSessionModel authSession = null;
    if (authSessionId != null) authSession = authSessionManager.getAuthenticationSessionByIdAndClient(realm, authSessionId, client, tabId);
    AuthenticationSessionModel authSessionCookie = authSessionManager.getCurrentAuthenticationSession(realm, client, tabId);

    if (authSession != null && authSessionCookie != null && !authSession.getParentSession().getId().equals(authSessionCookie.getParentSession().getId())) {
        event.detail(Details.REASON, "cookie does not match auth_session query parameter");
        event.error(Errors.INVALID_CODE);
        response = ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
        return null;

    }

    if (authSession != null) {
        session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession);
        return authSession;
    }

    if (authSessionCookie != null) {
        session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSessionCookie);
        return authSessionCookie;

    }

    // See if we are already authenticated and userSession with same ID exists.
    UserSessionModel userSession = authSessionManager.getUserSessionFromAuthCookie(realm);

    if (userSession != null) {
        LoginFormsProvider loginForm = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession)
                .setSuccess(Messages.ALREADY_LOGGED_IN);

        if (client == null) {
            loginForm.setAttribute(Constants.SKIP_LINK, true);
        }

        response = loginForm.createInfoPage();
        return null;
    }

    // Otherwise just try to restart from the cookie
    RootAuthenticationSessionModel existingRootAuthSession = authSessionManager.getCurrentRootAuthenticationSession(realm);
    response = restartAuthenticationSessionFromCookie(existingRootAuthSession);
    return null;
}