org.keycloak.services.messages.Messages Java Examples

The following examples show how to use org.keycloak.services.messages.Messages. 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: LoginActionsServiceChecks.java    From keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * Verifies whether the client denoted by client ID in token's {@code iss} ({@code issuedFor})
 * field both exists and is enabled.
 */
public static <T extends JsonWebToken> void checkIsClientValid(T token, ActionTokenContext<T> context) throws VerificationException {
    String clientId = token.getIssuedFor();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    ClientModel client = authSession == null ? null : authSession.getClient();

    try {
        checkIsClientValid(context.getSession(), client);

        if (clientId != null && ! Objects.equals(client.getClientId(), clientId)) {
            throw new ExplainedTokenVerificationException(token, Errors.CLIENT_NOT_FOUND, Messages.UNKNOWN_LOGIN_REQUESTER);
        }
    } catch (ExplainedVerificationException ex) {
        throw new ExplainedTokenVerificationException(token, ex);
    }
}
 
Example #2
Source File: RegistrationPassword.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: SamlService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response basicChecks(String samlRequest, String samlResponse) {
    if (!checkSsl()) {
        event.event(EventType.LOGIN);
        event.error(Errors.SSL_REQUIRED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
    }
    if (!realm.isEnabled()) {
        event.event(EventType.LOGIN_ERROR);
        event.error(Errors.REALM_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
    }

    if (samlRequest == null && samlResponse == null) {
        event.event(EventType.LOGIN);
        event.error(Errors.SAML_TOKEN_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);

    }
    return null;
}
 
Example #4
Source File: AccountCredentialResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Update a user label of specified credential of current user
 *
 * @param credentialId ID of the credential, which will be updated
 * @param userLabel new user label as JSON string
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{credentialId}/label")
@NoCache
public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
    if (credential == null) {
        throw new NotFoundException("Credential not found");
    }

    try {
        String label = JsonSerialization.readValue(userLabel, String.class);
        session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, label);
    } catch (IOException ioe) {
        throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST));
    }
}
 
Example #5
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * If there is a client whose SAML IDP-initiated SSO URL name is set to the
 * given {@code clientUrlName}, creates a fresh client session for that
 * client and returns a {@link ParsedCodeContext} object with that session.
 * Otherwise returns "client not found" response.
 *
 * @param clientUrlName
 * @return see description
 */
private ParsedCodeContext samlIdpInitiatedSSO(final String clientUrlName) {
    event.event(EventType.LOGIN);
    CacheControlUtil.noBackButtonCacheControlHeader();
    Optional<ClientModel> oClient = this.realmModel.getClients().stream()
      .filter(c -> Objects.equals(c.getAttribute(SamlProtocol.SAML_IDP_INITIATED_SSO_URL_NAME), clientUrlName))
      .findFirst();

    if (! oClient.isPresent()) {
        event.error(Errors.CLIENT_NOT_FOUND);
        return ParsedCodeContext.response(redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND));
    }

    LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
    SamlService samlService = (SamlService) factory.createProtocolEndpoint(realmModel, event);
    ResteasyProviderFactory.getInstance().injectProperties(samlService);
    AuthenticationSessionModel authSession = samlService.getOrCreateLoginSessionForIdpInitiatedSso(session, realmModel, oClient.get(), null);
    if (authSession == null) {
        event.error(Errors.INVALID_REDIRECT_URI);
        return ParsedCodeContext.response(redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI));
    }

    return ParsedCodeContext.clientSessionCode(new ClientSessionCode<>(session, this.realmModel, authSession));
}
 
Example #6
Source File: SAMLEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response handleLogoutResponse(SAMLDocumentHolder holder, StatusResponseType responseType, String relayState) {
    if (relayState == null) {
        logger.error("no valid user session");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
    }
    UserSessionModel userSession = session.sessions().getUserSession(realm, relayState);
    if (userSession == null) {
        logger.error("no valid user session");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR);
    }
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        logger.error("usersession in different state");
        event.event(EventType.LOGOUT);
        event.error(Errors.USER_SESSION_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
    }
    return AuthenticationManager.finishBrowserLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers);
}
 
Example #7
Source File: BasicAuthOTPAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean checkOtp(AuthenticationFlowContext context, String otp) {
    OTPCredentialModel preferredCredential = getCredentialProvider(context.getSession())
            .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser());
    boolean valid = getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(),
            new UserCredentialModel(preferredCredential.getId(), getCredentialProvider(context.getSession()).getType(), otp));

    if (!valid) {
        context.getEvent().user(context.getUser()).error(Errors.INVALID_USER_CREDENTIALS);
        if (context.getExecution().isRequired()){
            Response challengeResponse = challenge(context, Messages.INVALID_TOTP);
            context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challengeResponse);
        } else {
            context.attempted();
        }
        return false;
    }

    return true;
}
 
Example #8
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean shouldPerformAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, String providerId) {
    String noteFromSession = authSession.getAuthNote(LINKING_IDENTITY_PROVIDER);
    if (noteFromSession == null) {
        return false;
    }

    boolean linkingValid;
    if (userSession == null) {
        linkingValid = false;
    } else {
        String expectedNote = userSession.getId() + authSession.getClient().getClientId() + providerId;
        linkingValid = expectedNote.equals(noteFromSession);
    }

    if (linkingValid) {
        authSession.removeAuthNote(LINKING_IDENTITY_PROVIDER);
        return true;
    } else {
        throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.BROKER_LINKING_SESSION_EXPIRED);
    }
}
 
Example #9
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 #10
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 #11
Source File: LinkedAccountsResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String checkCommonPreconditions(String providerId) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    
    if (Validation.isEmpty(providerId)) {
        return Messages.MISSING_IDENTITY_PROVIDER;
    }
    
    if (!isValidProvider(providerId)) {
        return Messages.IDENTITY_PROVIDER_NOT_FOUND;
    }
    
    if (!user.isEnabled()) {
        return Messages.ACCOUNT_DISABLED;
    }
    
    return null;
}
 
Example #12
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 #13
Source File: SessionCodeChecks.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public boolean verifyActiveAndValidAction(String expectedAction, ClientSessionCode.ActionType actionType) {
    if (failed()) {
        return false;
    }

    if (!isActionActive(actionType)) {
        return false;
    }

    if (!clientCode.isValidAction(expectedAction)) {
        AuthenticationSessionModel authSession = getAuthenticationSession();
        if (AuthenticationSessionModel.Action.REQUIRED_ACTIONS.name().equals(authSession.getAction())) {
            logger.debugf("Incorrect action '%s' . User authenticated already.", authSession.getAction());
            response = showPageExpired(authSession);
            return false;
        } else {
            logger.errorf("Bad action. Expected action '%s', current action '%s'", expectedAction, authSession.getAction());
            response = ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.EXPIRED_CODE);
            return false;
        }
    }

    return true;
}
 
Example #14
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Response registerRequest(String authSessionId, String code, String execution, String clientId, String tabId, boolean isPostRequest) {
    event.event(EventType.REGISTER);
    if (!realm.isRegistrationAllowed()) {
        event.error(Errors.REGISTRATION_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REGISTRATION_NOT_ALLOWED);
    }

    SessionCodeChecks checks = checksForCode(authSessionId, code, execution, clientId, tabId, REGISTRATION_PATH);
    if (!checks.verifyActiveAndValidAction(AuthenticationSessionModel.Action.AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        return checks.getResponse();
    }

    AuthenticationSessionModel authSession = checks.getAuthenticationSession();

    processLocaleParam(authSession);

    AuthenticationManager.expireIdentityCookie(realm, session.getContext().getUri(), clientConnection);

    return processRegistration(checks.isActionRequest(), execution, authSession, null);
}
 
Example #15
Source File: AbstractIdentityFirstUsernameFormAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected UserModel lookupUser(AuthenticationFlowContext context, String username) {

        try {
            return KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
        } catch (ModelDuplicateException mde) {
            ServicesLogger.LOGGER.modelDuplicateException(mde);

            // Could happen during federation import
            if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
                setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER);
            } else {
                setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER);
            }
        }

        return null;
    }
 
Example #16
Source File: AccountFormService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void updateUsername(String username, UserModel user, KeycloakSession session) {
    RealmModel realm = session.getContext().getRealm();
    boolean usernameChanged = username == null || !user.getUsername().equals(username);
    if (realm.isEditUsernameAllowed() && !realm.isRegistrationEmailAsUsername()) {
        if (usernameChanged) {
            UserModel existing = session.users().getUserByUsername(username, realm);
            if (existing != null && !existing.getId().equals(user.getId())) {
                throw new ModelDuplicateException(Messages.USERNAME_EXISTS);
            }

            user.setUsername(username);
        }
    } else if (usernameChanged) {

    }
}
 
Example #17
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 #18
Source File: RequireRoleAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: ConsoleVerifyEmail.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent().clone().event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, context.getUser().getEmail());
    String code = context.getAuthenticationSession().getAuthNote(Constants.VERIFY_EMAIL_CODE);
    if (code == null) {
        requiredActionChallenge(context);
        return;
    }

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String emailCode = formData.getFirst(EMAIL_CODE);

    if (!code.equals(emailCode)) {
        context.challenge(
                challenge(context).message(Messages.INVALID_CODE)
        );
        event.error(Errors.INVALID_CODE);
        return;
    }
    event.success();
    context.success();
}
 
Example #20
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 #21
Source File: SAMLEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response basicChecks(String samlRequest, String samlResponse) {
    if (!checkSsl()) {
        event.event(EventType.LOGIN);
        event.error(Errors.SSL_REQUIRED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.HTTPS_REQUIRED);
    }
    if (!realm.isEnabled()) {
        event.event(EventType.LOGIN_ERROR);
        event.error(Errors.REALM_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.REALM_NOT_ENABLED);
    }

    if (samlRequest == null && samlResponse == null) {
        event.event(EventType.LOGIN);
        event.error(Errors.INVALID_REQUEST);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);

    }
    return null;
}
 
Example #22
Source File: SessionCodeChecks.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response restartAuthenticationSessionFromCookie(RootAuthenticationSessionModel existingRootSession) {
    logger.debug("Authentication session not found. Trying to restart from cookie.");
    AuthenticationSessionModel authSession = null;

    try {
        authSession = RestartLoginCookie.restartSession(session, realm, existingRootSession, clientId);
    } catch (Exception e) {
        ServicesLogger.LOGGER.failedToParseRestartLoginCookie(e);
    }

    if (authSession != null) {

        event.clone();
        event.detail(Details.RESTART_AFTER_TIMEOUT, "true");
        event.error(Errors.EXPIRED_CODE);

        String warningMessage = Messages.LOGIN_TIMEOUT;
        authSession.setAuthNote(LoginActionsService.FORWARDED_ERROR_MESSAGE_NOTE, warningMessage);

        String flowPath = authSession.getClientNote(AuthorizationEndpointBase.APP_INITIATED_FLOW);
        if (flowPath == null) {
            flowPath = LoginActionsService.AUTHENTICATE_PATH;
        }

        URI redirectUri = getLastExecutionUrl(flowPath, null, authSession.getTabId());
        logger.debugf("Authentication session restart from cookie succeeded. Redirecting to %s", redirectUri);
        return Response.status(Response.Status.FOUND).location(redirectUri).build();
    } else {
        // Finally need to show error as all the fallbacks failed
        event.error(Errors.INVALID_CODE);
        return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, Messages.INVALID_CODE);
    }
}
 
Example #23
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@NoCache
@Path("/after-post-broker-login")
public Response afterPostBrokerLoginFlow(@QueryParam(LoginActionsService.SESSION_CODE) String code,
                                         @QueryParam("client_id") String clientId,
                                         @QueryParam(Constants.TAB_ID) String tabId) {
    ParsedCodeContext parsedCode = parseSessionCode(code, clientId, tabId);
    if (parsedCode.response != null) {
        return parsedCode.response;
    }
    AuthenticationSessionModel authenticationSession = parsedCode.clientSessionCode.getClientSession();

    try {
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authenticationSession, PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession. Note " + PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT + " was null");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authenticationSession);

        String wasFirstBrokerLoginNote = authenticationSession.getAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);
        boolean wasFirstBrokerLogin = Boolean.parseBoolean(wasFirstBrokerLoginNote);

        // Ensure the post-broker-login flow was successfully finished
        String authStateNoteKey = PostBrokerLoginConstants.PBL_AUTH_STATE_PREFIX + context.getIdpConfig().getAlias();
        String authState = authenticationSession.getAuthNote(authStateNoteKey);
        if (!Boolean.parseBoolean(authState)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that post-broker-login flow was finished");
        }

        // remove notes
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);
        authenticationSession.removeAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN);

        return afterPostBrokerLoginFlowSuccess(authenticationSession, context, wasFirstBrokerLogin, parsedCode.clientSessionCode);
    } catch (IdentityBrokerException e) {
        return redirectToErrorPage(authenticationSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
 
Example #24
Source File: IdpVerifyAccountLinkActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public IdpVerifyAccountLinkActionTokenHandler() {
    super(
      IdpVerifyAccountLinkActionToken.TOKEN_TYPE,
      IdpVerifyAccountLinkActionToken.class,
      Messages.STALE_CODE,
      EventType.IDENTITY_PROVIDER_LINK_ACCOUNT,
      Errors.INVALID_TOKEN
    );
}
 
Example #25
Source File: ExecuteActionsActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Predicate<? super ExecuteActionsActionToken>[] getVerifiers(ActionTokenContext<ExecuteActionsActionToken> tokenContext) {
    return TokenUtils.predicates(
      TokenUtils.checkThat(
        // either redirect URI is not specified or must be valid for the client
        t -> t.getRedirectUri() == null
             || RedirectUtils.verifyRedirectUri(tokenContext.getSession(), t.getRedirectUri(),
                  tokenContext.getAuthenticationSession().getClient()) != null,
        Errors.INVALID_REDIRECT_URI,
        Messages.INVALID_REDIRECT_URI
      )
    );
}
 
Example #26
Source File: ExecuteActionsActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ExecuteActionsActionTokenHandler() {
    super(
      ExecuteActionsActionToken.TOKEN_TYPE,
      ExecuteActionsActionToken.class,
      Messages.INVALID_CODE,
      EventType.EXECUTE_ACTIONS,
      Errors.NOT_ALLOWED
    );
}
 
Example #27
Source File: ResetCredentialsActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Predicate<? super ResetCredentialsActionToken>[] getVerifiers(ActionTokenContext<ResetCredentialsActionToken> tokenContext) {
    return new Predicate[] {
        TokenUtils.checkThat(tokenContext.getRealm()::isResetPasswordAllowed, Errors.NOT_ALLOWED, Messages.RESET_CREDENTIAL_NOT_ALLOWED),

        new IsActionRequired(tokenContext, Action.AUTHENTICATE)
    };
}
 
Example #28
Source File: LoginActionsService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response handleActionTokenVerificationException(ActionTokenContext<?> tokenContext, VerificationException ex, String eventError, String errorMessage) {
    if (tokenContext != null && tokenContext.getAuthenticationSession() != null) {
        new AuthenticationSessionManager(session).removeAuthenticationSession(realm, tokenContext.getAuthenticationSession(), true);
    }

    event
      .detail(Details.REASON, ex == null ? "<unknown>" : ex.getMessage())
      .error(eventError == null ? Errors.INVALID_CODE : eventError);
    return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, errorMessage == null ? Messages.INVALID_CODE : errorMessage);
}
 
Example #29
Source File: VerifyEmailActionTokenHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public VerifyEmailActionTokenHandler() {
    super(
      VerifyEmailActionToken.TOKEN_TYPE,
      VerifyEmailActionToken.class,
      Messages.STALE_VERIFY_EMAIL_LINK,
      EventType.VERIFY_EMAIL,
      Errors.INVALID_TOKEN
    );
}
 
Example #30
Source File: ConsoleUpdatePassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void processAction(RequiredActionContext context) {
    EventBuilder event = context.getEvent();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    event.event(EventType.UPDATE_PASSWORD);
    String passwordNew = formData.getFirst(PASSWORD_NEW);
    String passwordConfirm = formData.getFirst(PASSWORD_CONFIRM);

    EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR)
            .client(context.getAuthenticationSession().getClient())
            .user(context.getAuthenticationSession().getAuthenticatedUser());

    if (Validation.isBlank(passwordNew)) {
        context.challenge(challenge(context).message(Messages.MISSING_PASSWORD));
        errorEvent.error(Errors.PASSWORD_MISSING);
        return;
    } else if (!passwordNew.equals(passwordConfirm)) {
        context.challenge(challenge(context).message(Messages.NOTMATCH_PASSWORD));
        errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
        return;
    }

    try {
        context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew, false));
        context.success();
    } catch (ModelException me) {
        errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
        context.challenge(challenge(context).text(me.getMessage()));
        return;
    } catch (Exception ape) {
        errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
        context.challenge(challenge(context).text(ape.getMessage()));
        return;
    }
}