org.keycloak.models.utils.FormMessage Java Examples
The following examples show how to use
org.keycloak.models.utils.FormMessage.
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: IdentityBrokerService.java From keycloak with Apache License 2.0 | 6 votes |
protected Response browserAuthentication(AuthenticationSessionModel authSession, String errorMessage) { this.event.event(EventType.LOGIN); AuthenticationFlowModel flow = AuthenticationFlowResolver.resolveBrowserFlow(authSession); String flowId = flow.getId(); AuthenticationProcessor processor = new AuthenticationProcessor(); processor.setAuthenticationSession(authSession) .setFlowPath(LoginActionsService.AUTHENTICATE_PATH) .setFlowId(flowId) .setBrowserFlow(true) .setConnection(clientConnection) .setEventBuilder(event) .setRealm(realmModel) .setSession(session) .setUriInfo(session.getContext().getUri()) .setRequest(request); if (errorMessage != null) processor.setForwardedErrorMessage(new FormMessage(null, errorMessage)); try { CacheControlUtil.noBackButtonCacheControlHeader(); return processor.authenticate(); } catch (Exception e) { return processor.handleBrowserException(e); } }
Example #2
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 6 votes |
/** * Handle messages to be shown on the page - set them to template attributes * * @param locale to be used for message text loading * @param messagesBundle to be used for message text loading * @see #messageType * @see #messages */ protected void handleMessages(Locale locale, Properties messagesBundle) { MessagesPerFieldBean messagesPerField = new MessagesPerFieldBean(); if (messages != null) { MessageBean wholeMessage = new MessageBean(null, messageType); for (FormMessage message : this.messages) { String formattedMessageText = formatMessage(message, messagesBundle, locale); if (formattedMessageText != null) { wholeMessage.appendSummaryLine(formattedMessageText); messagesPerField.addMessage(message.getField(), formattedMessageText, messageType); } } attributes.put("message", wholeMessage); } else { attributes.put("message", null); } attributes.put("messagesPerField", messagesPerField); }
Example #3
Source File: Validation.java From keycloak with Apache License 2.0 | 6 votes |
public static List<FormMessage> validateUpdateProfileForm(RealmModel realm, MultivaluedMap<String, String> formData, boolean userNameRequired) { List<FormMessage> errors = new ArrayList<>(); if (!realm.isRegistrationEmailAsUsername() && userNameRequired && isBlank(formData.getFirst(FIELD_USERNAME))) { addError(errors, FIELD_USERNAME, Messages.MISSING_USERNAME); } if (isBlank(formData.getFirst(FIELD_FIRST_NAME))) { addError(errors, FIELD_FIRST_NAME, Messages.MISSING_FIRST_NAME); } if (isBlank(formData.getFirst(FIELD_LAST_NAME))) { addError(errors, FIELD_LAST_NAME, Messages.MISSING_LAST_NAME); } if (isBlank(formData.getFirst(FIELD_EMAIL))) { addError(errors, FIELD_EMAIL, Messages.MISSING_EMAIL); } else if (!isEmailValid(formData.getFirst(FIELD_EMAIL))) { addError(errors, FIELD_EMAIL, Messages.INVALID_EMAIL); } return errors; }
Example #4
Source File: FreeMarkerAccountProvider.java From keycloak with Apache License 2.0 | 6 votes |
/** * Handle messages to be shown on the page - set them to template attributes * * @param locale to be used for message text loading * @param messagesBundle to be used for message text loading * @param attributes template attributes to messages related info to * @see #messageType * @see #messages */ protected void handleMessages(Locale locale, Properties messagesBundle, Map<String, Object> attributes) { MessagesPerFieldBean messagesPerField = new MessagesPerFieldBean(); if (messages != null) { MessageBean wholeMessage = new MessageBean(null, messageType); for (FormMessage message : this.messages) { String formattedMessageText = formatMessage(message, messagesBundle, locale); if (formattedMessageText != null) { wholeMessage.appendSummaryLine(formattedMessageText); messagesPerField.addMessage(message.getField(), formattedMessageText, messageType); } } attributes.put("message", wholeMessage); } attributes.put("messagesPerField", messagesPerField); }
Example #5
Source File: RecaptchaUsernamePasswordForm.java From keycloak-login-recaptcha with Apache License 2.0 | 6 votes |
@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 #6
Source File: RegistrationRecaptcha.java From keycloak with Apache License 2.0 | 6 votes |
@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 #7
Source File: RequireRoleAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 6 votes |
@Override public void authenticate(AuthenticationFlowContext context) { AuthenticatorConfigModel configModel = context.getAuthenticatorConfig(); String roleName = configModel.getConfig().get(RequireRoleAuthenticatorFactory.ROLE); RealmModel realm = context.getRealm(); UserModel user = context.getUser(); if (userHasRole(realm, user, roleName)) { context.success(); return; } LOG.debugf("Access denied because of missing role. realm=%s username=%s role=%s", realm.getName(), user.getUsername(), roleName); context.getEvent().user(user); context.getEvent().error(Errors.NOT_ALLOWED); context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS)); }
Example #8
Source File: RegistrationPassword.java From keycloak with Apache License 2.0 | 6 votes |
@Override public void validate(ValidationContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); List<FormMessage> errors = new ArrayList<>(); context.getEvent().detail(Details.REGISTER_METHOD, "form"); if (Validation.isBlank(formData.getFirst(RegistrationPage.FIELD_PASSWORD))) { errors.add(new FormMessage(RegistrationPage.FIELD_PASSWORD, Messages.MISSING_PASSWORD)); } else if (!formData.getFirst(RegistrationPage.FIELD_PASSWORD).equals(formData.getFirst(RegistrationPage.FIELD_PASSWORD_CONFIRM))) { errors.add(new FormMessage(RegistrationPage.FIELD_PASSWORD_CONFIRM, Messages.INVALID_PASSWORD_CONFIRM)); } if (formData.getFirst(RegistrationPage.FIELD_PASSWORD) != null) { PolicyError err = context.getSession().getProvider(PasswordPolicyManagerProvider.class).validate(context.getRealm().isRegistrationEmailAsUsername() ? formData.getFirst(RegistrationPage.FIELD_EMAIL) : formData.getFirst(RegistrationPage.FIELD_USERNAME), formData.getFirst(RegistrationPage.FIELD_PASSWORD)); if (err != null) errors.add(new FormMessage(RegistrationPage.FIELD_PASSWORD, err.getMessage(), err.getParameters())); } if (errors.size() > 0) { context.error(Errors.INVALID_REGISTRATION); formData.remove(RegistrationPage.FIELD_PASSWORD); formData.remove(RegistrationPage.FIELD_PASSWORD_CONFIRM); context.validationError(formData, errors); return; } else { context.success(); } }
Example #9
Source File: FormAuthenticationFlow.java From keycloak with Apache License 2.0 | 6 votes |
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 #10
Source File: ThirdPartyMfaAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 6 votes |
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 #11
Source File: RegistrationRecaptcha.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void validate(ValidationContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); List<FormMessage> errors = new ArrayList<>(); boolean success = false; context.getEvent().detail(Details.REGISTER_METHOD, "form"); String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { context.success(); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); context.error(Errors.INVALID_REGISTRATION); context.validationError(formData, errors); context.excludeOtherErrors(); return; } }
Example #12
Source File: FreeMarkerAccountProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public AccountProvider setErrors(Response.Status status, List<FormMessage> messages) { this.status = status; this.messageType = MessageType.ERROR; this.messages = new ArrayList<>(messages); return this; }
Example #13
Source File: FreeMarkerAccountProvider.java From keycloak with Apache License 2.0 | 5 votes |
protected String formatMessage(FormMessage message, Properties messagesBundle, Locale locale) { if (message == null) return null; if (messagesBundle.containsKey(message.getMessage())) { return new MessageFormat(messagesBundle.getProperty(message.getMessage()), locale).format(message.getParameters()); } else { return message.getMessage(); } }
Example #14
Source File: X509ClientCertificateAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 #15
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
@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 #16
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public LoginFormsProvider addError(FormMessage errorMessage) { if (this.messageType != MessageType.ERROR) { this.messageType = null; this.messages = null; } if (messages == null) { this.messageType = MessageType.ERROR; this.messages = new LinkedList<>(); } this.messages.add(errorMessage); return this; }
Example #17
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public LoginFormsProvider setErrors(List<FormMessage> messages) { if (messages == null) return this; this.messageType = MessageType.ERROR; this.messages = new ArrayList<>(messages); return this; }
Example #18
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
protected String formatMessage(FormMessage message, Properties messagesBundle, Locale locale) { if (message == null) return null; if (messagesBundle.containsKey(message.getMessage())) { return new MessageFormat(messagesBundle.getProperty(message.getMessage()), locale).format(message.getParameters()); } else { return message.getMessage(); } }
Example #19
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public String getMessage(String message, String... parameters) { Theme theme; try { theme = getTheme(); } catch (IOException e) { logger.error("Failed to create theme", e); throw new RuntimeException("Failed to create theme"); } Locale locale = session.getContext().resolveLocale(user); Properties messagesBundle = handleThemeResources(theme, locale); FormMessage msg = new FormMessage(message, (Object[]) parameters); return formatMessage(msg, messagesBundle, locale); }
Example #20
Source File: FreeMarkerLoginFormsProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public String getMessage(String message) { Theme theme; try { theme = getTheme(); } catch (IOException e) { logger.error("Failed to create theme", e); throw new RuntimeException("Failed to create theme"); } Locale locale = session.getContext().resolveLocale(user); Properties messagesBundle = handleThemeResources(theme, locale); FormMessage msg = new FormMessage(null, message); return formatMessage(msg, messagesBundle, locale); }
Example #21
Source File: MinPasswordAgeAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 5 votes |
@Override public void authenticate(AuthenticationFlowContext context) { RealmModel realm = context.getRealm(); UserModel user = context.getUser(); Map<String, String> config = (context.getAuthenticatorConfig() == null ? Collections.emptyMap() : context.getAuthenticatorConfig().getConfig()); List<CredentialModel> passwords = context.getSession().userCredentialManager().getStoredCredentialsByType(realm, user, PasswordCredentialModel.TYPE); if (!passwords.isEmpty()) { CredentialModel passwordCredential = passwords.get(0); Instant creationTime = Instant.ofEpochMilli(passwordCredential.getCreatedDate()); Duration minPasswordAge = Duration.parse(config.getOrDefault(MIN_PASSWORD_AGE_DURATION, "PT15M")); if (creationTime.isAfter(Instant.now().minus(minPasswordAge))) { log.warnf("Access denied because of min password age. realm=%s username=%s", realm.getName(), user.getUsername()); context.getEvent().user(user); context.getEvent().error(Errors.NOT_ALLOWED); context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS)); return; } } context.success(); }
Example #22
Source File: AuthenticationProcessor.java From keycloak with Apache License 2.0 | 5 votes |
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 #23
Source File: Validation.java From keycloak with Apache License 2.0 | 5 votes |
public static List<FormMessage> validateRegistrationForm(KeycloakSession session, RealmModel realm, MultivaluedMap<String, String> formData, List<String> requiredCredentialTypes, PasswordPolicy policy) { List<FormMessage> errors = new ArrayList<>(); if (!realm.isRegistrationEmailAsUsername() && isBlank(formData.getFirst(FIELD_USERNAME))) { addError(errors, FIELD_USERNAME, Messages.MISSING_USERNAME); } if (isBlank(formData.getFirst(FIELD_FIRST_NAME))) { addError(errors, FIELD_FIRST_NAME, Messages.MISSING_FIRST_NAME); } if (isBlank(formData.getFirst(FIELD_LAST_NAME))) { addError(errors, FIELD_LAST_NAME, Messages.MISSING_LAST_NAME); } if (isBlank(formData.getFirst(FIELD_EMAIL))) { addError(errors, FIELD_EMAIL, Messages.MISSING_EMAIL); } else if (!isEmailValid(formData.getFirst(FIELD_EMAIL))) { addError(errors, FIELD_EMAIL, Messages.INVALID_EMAIL); } if (requiredCredentialTypes.contains(CredentialRepresentation.PASSWORD)) { if (isBlank(formData.getFirst(FIELD_PASSWORD))) { addError(errors, FIELD_PASSWORD, Messages.MISSING_PASSWORD); } else if (!formData.getFirst(FIELD_PASSWORD).equals(formData.getFirst(FIELD_PASSWORD_CONFIRM))) { addError(errors, FIELD_PASSWORD_CONFIRM, Messages.INVALID_PASSWORD_CONFIRM); } } if (formData.getFirst(FIELD_PASSWORD) != null) { PolicyError err = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm.isRegistrationEmailAsUsername() ? formData.getFirst(FIELD_EMAIL) : formData.getFirst(FIELD_USERNAME), formData.getFirst(FIELD_PASSWORD)); if (err != null) errors.add(new FormMessage(FIELD_PASSWORD, err.getMessage(), err.getParameters())); } return errors; }
Example #24
Source File: RegistrationValidateMobileFormAction.java From keycloak-extension-playground with Apache License 2.0 | 5 votes |
@Override public void validate(ValidationContext context) { // called when the user submits the registration form MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); List<FormMessage> errors = new ArrayList<>(); context.getEvent().detail(Details.REGISTER_METHOD, "form"); String eventError = Errors.INVALID_REGISTRATION; String mobilePhoneNumber = formData.getFirst(MOBILE_NUMBER_FIELD); if (Validation.isBlank(mobilePhoneNumber)) { errors.add(new FormMessage(MOBILE_NUMBER_FIELD, "missingMobileMessage")); } else if (!MobileValidation.isPhoneNumberValid(mobilePhoneNumber)) { context.getEvent().detail("mobile_phone_number", mobilePhoneNumber); errors.add(new FormMessage(MOBILE_NUMBER_FIELD, "invalidMobileMessage")); } if (errors.isEmpty()) { context.success(); return; } context.error(eventError); context.validationError(formData, errors); }
Example #25
Source File: IdentityBrokerService.java From keycloak with Apache License 2.0 | 5 votes |
private Response redirectToAccountErrorPage(AuthenticationSessionModel authSession, String message, Object ... parameters) { fireErrorEvent(message); FormMessage errorMessage = new FormMessage(message, parameters); try { String serializedError = JsonSerialization.writeValueAsString(errorMessage); authSession.setAuthNote(AccountFormService.ACCOUNT_MGMT_FORWARDED_ERROR_NOTE, serializedError); } catch (IOException ioe) { throw new RuntimeException(ioe); } URI accountServiceUri = UriBuilder.fromUri(authSession.getRedirectUri()).queryParam(Constants.TAB_ID, authSession.getTabId()).build(); return Response.status(302).location(accountServiceUri).build(); }
Example #26
Source File: AccessPolicyAuthenticator.java From keycloak-extension-playground with Apache License 2.0 | 5 votes |
@Override public void authenticate(AuthenticationFlowContext context) { AuthenticatorConfigModel configModel = context.getAuthenticatorConfig(); if (configModel == null) { context.attempted(); return; } String accessPolicyJson = configModel.getConfig().get(AccessPolicyAuthenticatorFactory.ACCESS_POLICY); if (accessPolicyJson == null) { context.attempted(); return; } AccessPolicy accessPolicy = accessPolicyParser.parse(accessPolicyJson); RealmModel realm = context.getRealm(); ClientModel client = context.getAuthenticationSession().getClient(); UserModel user = context.getUser(); if (!accessPolicy.hasAccess(realm, user, client)) { log.debugf("Access denied because of access policy. realm=%s client=%s username=%s", realm.getName(), client.getClientId(), user.getUsername()); context.getEvent().user(user); context.getEvent().error(Errors.NOT_ALLOWED); context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS)); return; } context.success(); }
Example #27
Source File: AccountFormService.java From keycloak with Apache License 2.0 | 5 votes |
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 #28
Source File: RecaptchaUsernamePasswordForm.java From keycloak-login-recaptcha with Apache License 2.0 | 5 votes |
@Override public void action(AuthenticationFlowContext context) { if (logger.isDebugEnabled()) { logger.debug("action(AuthenticationFlowContext) - start"); } MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); List<FormMessage> errors = new ArrayList<>(); boolean success = false; context.getEvent().detail(Details.AUTH_METHOD, "auth_method"); String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { super.action(context); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); // context.error(Errors.INVALID_REGISTRATION); // context.validationError(formData, errors); // context.excludeOtherErrors(); return; } if (logger.isDebugEnabled()) { logger.debug("action(AuthenticationFlowContext) - end"); } }
Example #29
Source File: AuthenticationProcessor.java From keycloak with Apache License 2.0 | 4 votes |
@Override public FormMessage getForwardedErrorMessage() { return AuthenticationProcessor.this.forwardedErrorMessage; }
Example #30
Source File: AccountFormService.java From keycloak with Apache License 2.0 | 4 votes |
/** * Update account information. * <p> * Form params: * <p> * firstName * lastName * email * * @param formData * @return */ @Path("/") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response processAccountUpdate(final MultivaluedMap<String, String> formData) { if (auth == null) { return login(null); } auth.require(AccountRoles.MANAGE_ACCOUNT); String action = formData.getFirst("submitAction"); if (action != null && action.equals("Cancel")) { setReferrerOnPage(); return account.createResponse(AccountPages.ACCOUNT); } csrfCheck(formData); UserModel user = auth.getUser(); event.event(EventType.UPDATE_PROFILE).client(auth.getClient()).user(auth.getUser()); List<FormMessage> errors = Validation.validateUpdateProfileForm(realm, formData); if (errors != null && !errors.isEmpty()) { setReferrerOnPage(); return account.setErrors(Status.OK, errors).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } try { updateUsername(formData.getFirst("username"), user, session); updateEmail(formData.getFirst("email"), user, session, event); user.setFirstName(formData.getFirst("firstName")); user.setLastName(formData.getFirst("lastName")); AttributeFormDataProcessor.process(formData, realm, user); event.success(); setReferrerOnPage(); return account.setSuccess(Messages.ACCOUNT_UPDATED).createResponse(AccountPages.ACCOUNT); } catch (ReadOnlyException roe) { setReferrerOnPage(); return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_USER).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } catch (ModelDuplicateException mde) { setReferrerOnPage(); return account.setError(Response.Status.CONFLICT, mde.getMessage()).setProfileFormData(formData).createResponse(AccountPages.ACCOUNT); } }