Search in sources :

Example 86 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class ForgottenPasswordServlet method forwardUserBasedOnRecoveryMethod.

private void forwardUserBasedOnRecoveryMethod(final PwmRequest pwmRequest, final IdentityVerificationMethod method) throws ServletException, PwmUnrecoverableException, IOException {
    LOGGER.debug(pwmRequest, "attempting to forward request to handle verification method " + method.toString());
    final ForgottenPasswordBean forgottenPasswordBean = forgottenPasswordBean(pwmRequest);
    ForgottenPasswordUtil.verifyRequirementsForAuthMethod(pwmRequest, forgottenPasswordBean, method);
    switch(method) {
        case PREVIOUS_AUTH:
            {
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "previous authentication is required, but user has not previously authenticated"));
            }
        case ATTRIBUTES:
            {
                pwmRequest.addFormInfoToRequestAttr(forgottenPasswordBean.getAttributeForm(), Collections.emptyMap(), false, false);
                pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_ATTRIBUTES);
            }
            break;
        case CHALLENGE_RESPONSES:
            {
                pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordChallengeSet, forgottenPasswordBean.getPresentableChallengeSet());
                pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_RESPONSES);
            }
            break;
        case OTP:
            {
                pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordOtpRecord, ForgottenPasswordUtil.readUserInfo(pwmRequest, forgottenPasswordBean).getOtpUserRecord());
                pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_ENTER_OTP);
            }
            break;
        case TOKEN:
            {
                final ForgottenPasswordBean.Progress progress = forgottenPasswordBean.getProgress();
                final List<TokenDestinationItem> tokenDestinations = ForgottenPasswordUtil.figureAvailableTokenDestinations(pwmRequest, forgottenPasswordBean);
                if (progress.getTokenDestination() == null) {
                    final boolean autoSelect = Boolean.parseBoolean(pwmRequest.getConfig().readAppProperty(AppProperty.FORGOTTEN_PASSWORD_TOKEN_AUTO_SELECT_DEST));
                    if (autoSelect && tokenDestinations.size() == 1) {
                        final TokenDestinationItem singleItem = tokenDestinations.iterator().next();
                        progress.setTokenDestination(singleItem);
                    }
                }
                if (progress.getTokenDestination() == null) {
                    forwardToTokenChoiceJsp(pwmRequest);
                    return;
                }
                if (!progress.isTokenSent()) {
                    final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo(pwmRequest, forgottenPasswordBean);
                    ForgottenPasswordUtil.initializeAndSendToken(pwmRequest, userInfo, progress.getTokenDestination());
                    progress.setTokenSent(true);
                }
                if (!progress.getSatisfiedMethods().contains(IdentityVerificationMethod.TOKEN)) {
                    forwardToEnterTokenJsp(pwmRequest);
                    return;
                }
            }
            break;
        case REMOTE_RESPONSES:
            {
                final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo(pwmRequest, forgottenPasswordBean);
                final VerificationMethodSystem remoteMethod;
                if (forgottenPasswordBean.getProgress().getRemoteRecoveryMethod() == null) {
                    remoteMethod = new RemoteVerificationMethod();
                    remoteMethod.init(pwmRequest.getPwmApplication(), userInfo, pwmRequest.getSessionLabel(), pwmRequest.getLocale());
                    forgottenPasswordBean.getProgress().setRemoteRecoveryMethod(remoteMethod);
                } else {
                    remoteMethod = forgottenPasswordBean.getProgress().getRemoteRecoveryMethod();
                }
                final List<VerificationMethodSystem.UserPrompt> prompts = remoteMethod.getCurrentPrompts();
                final String displayInstructions = remoteMethod.getCurrentDisplayInstructions();
                pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordPrompts, new ArrayList<>(prompts));
                pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordInstructions, displayInstructions);
                pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_REMOTE);
            }
            break;
        case OAUTH:
            forgottenPasswordBean.getProgress().setInProgressVerificationMethod(IdentityVerificationMethod.OAUTH);
            final ForgottenPasswordProfile forgottenPasswordProfile = ForgottenPasswordUtil.forgottenPasswordProfile(pwmRequest.getPwmApplication(), forgottenPasswordBean);
            final OAuthSettings oAuthSettings = OAuthSettings.forForgottenPassword(forgottenPasswordProfile);
            final OAuthMachine oAuthMachine = new OAuthMachine(oAuthSettings);
            pwmRequest.getPwmApplication().getSessionStateService().saveSessionBeans(pwmRequest);
            final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
            oAuthMachine.redirectUserToOAuthServer(pwmRequest, null, userIdentity, forgottenPasswordProfile.getIdentifier());
            break;
        default:
            throw new UnsupportedOperationException("unexpected method during forward: " + method.toString());
    }
}
Also used : ForgottenPasswordProfile(password.pwm.config.profile.ForgottenPasswordProfile) UserIdentity(password.pwm.bean.UserIdentity) ArrayList(java.util.ArrayList) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) UserInfo(password.pwm.ldap.UserInfo) OAuthMachine(password.pwm.http.servlet.oauth.OAuthMachine) TokenDestinationItem(password.pwm.bean.TokenDestinationItem) VerificationMethodSystem(password.pwm.VerificationMethodSystem) ErrorInformation(password.pwm.error.ErrorInformation) List(java.util.List) ArrayList(java.util.ArrayList) OAuthSettings(password.pwm.http.servlet.oauth.OAuthSettings) ForgottenPasswordBean(password.pwm.http.bean.ForgottenPasswordBean)

Example 87 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class ForgottenPasswordServlet method nextStep.

@Override
@SuppressWarnings("checkstyle:MethodLength")
protected void nextStep(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmRequest.getConfig();
    final ForgottenPasswordBean forgottenPasswordBean = forgottenPasswordBean(pwmRequest);
    final ForgottenPasswordBean.RecoveryFlags recoveryFlags = forgottenPasswordBean.getRecoveryFlags();
    final ForgottenPasswordBean.Progress progress = forgottenPasswordBean.getProgress();
    // check for identified user;
    if (forgottenPasswordBean.getUserIdentity() == null && !forgottenPasswordBean.isBogusUser()) {
        pwmRequest.addFormInfoToRequestAttr(PwmSetting.FORGOTTEN_PASSWORD_SEARCH_FORM, false, false);
        pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_SEARCH);
        return;
    }
    final ForgottenPasswordProfile forgottenPasswordProfile = ForgottenPasswordUtil.forgottenPasswordProfile(pwmRequest.getPwmApplication(), forgottenPasswordBean);
    {
        final Map<String, ForgottenPasswordProfile> profileIDList = pwmRequest.getConfig().getForgottenPasswordProfiles();
        final String profileDebugMsg = forgottenPasswordProfile != null && profileIDList != null && profileIDList.size() > 1 ? " profile=" + forgottenPasswordProfile.getIdentifier() + ", " : "";
        LOGGER.trace(pwmRequest, "entering forgotten password progress engine: " + profileDebugMsg + "flags=" + JsonUtil.serialize(recoveryFlags) + ", " + "progress=" + JsonUtil.serialize(progress));
    }
    if (forgottenPasswordProfile == null) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_NO_PROFILE_ASSIGNED));
    }
    // check for previous authentication
    if (recoveryFlags.getRequiredAuthMethods().contains(IdentityVerificationMethod.PREVIOUS_AUTH) || recoveryFlags.getOptionalAuthMethods().contains(IdentityVerificationMethod.PREVIOUS_AUTH)) {
        if (!progress.getSatisfiedMethods().contains(IdentityVerificationMethod.PREVIOUS_AUTH)) {
            final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
            final String userGuid = LdapOperationsHelper.readLdapGuidValue(pwmApplication, pwmRequest.getSessionLabel(), userIdentity, true);
            if (ForgottenPasswordUtil.checkAuthRecord(pwmRequest, userGuid)) {
                LOGGER.debug(pwmRequest, "marking " + IdentityVerificationMethod.PREVIOUS_AUTH + " method as satisfied");
                progress.getSatisfiedMethods().add(IdentityVerificationMethod.PREVIOUS_AUTH);
            }
        }
    }
    // dispatch required auth methods.
    for (final IdentityVerificationMethod method : recoveryFlags.getRequiredAuthMethods()) {
        if (!progress.getSatisfiedMethods().contains(method)) {
            forwardUserBasedOnRecoveryMethod(pwmRequest, method);
            return;
        }
    }
    // redirect if an verification method is in progress
    if (progress.getInProgressVerificationMethod() != null) {
        if (progress.getSatisfiedMethods().contains(progress.getInProgressVerificationMethod())) {
            progress.setInProgressVerificationMethod(null);
        } else {
            pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordOptionalPageView, "true");
            forwardUserBasedOnRecoveryMethod(pwmRequest, progress.getInProgressVerificationMethod());
            return;
        }
    }
    // check if more optional methods required
    if (recoveryFlags.getMinimumOptionalAuthMethods() > 0) {
        final Set<IdentityVerificationMethod> satisfiedOptionalMethods = ForgottenPasswordUtil.figureSatisfiedOptionalAuthMethods(recoveryFlags, progress);
        if (satisfiedOptionalMethods.size() < recoveryFlags.getMinimumOptionalAuthMethods()) {
            final Set<IdentityVerificationMethod> remainingAvailableOptionalMethods = ForgottenPasswordUtil.figureRemainingAvailableOptionalAuthMethods(pwmRequest, forgottenPasswordBean);
            if (remainingAvailableOptionalMethods.isEmpty()) {
                final String errorMsg = "additional optional verification methods are needed, however all available optional verification methods have been satisfied by user";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_RECOVERY_SEQUENCE_INCOMPLETE, errorMsg);
                LOGGER.error(pwmRequest, errorInformation);
                pwmRequest.respondWithError(errorInformation);
                return;
            } else {
                if (remainingAvailableOptionalMethods.size() == 1) {
                    final IdentityVerificationMethod remainingMethod = remainingAvailableOptionalMethods.iterator().next();
                    LOGGER.debug(pwmRequest, "only 1 remaining available optional verification method, will redirect to " + remainingMethod.toString());
                    forwardUserBasedOnRecoveryMethod(pwmRequest, remainingMethod);
                    progress.setInProgressVerificationMethod(remainingMethod);
                    return;
                }
            }
            processVerificationChoice(pwmRequest);
            return;
        }
    }
    if (progress.getSatisfiedMethods().isEmpty()) {
        final String errorMsg = "forgotten password recovery sequence completed, but user has not actually satisfied any verification methods";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_RECOVERY_SEQUENCE_INCOMPLETE, errorMsg);
        LOGGER.error(pwmRequest, errorInformation);
        clearForgottenPasswordBean(pwmRequest);
        throw new PwmUnrecoverableException(errorInformation);
    }
    {
        final int satisfiedMethods = progress.getSatisfiedMethods().size();
        final int totalMethodsNeeded = recoveryFlags.getRequiredAuthMethods().size() + recoveryFlags.getMinimumOptionalAuthMethods();
        if (satisfiedMethods < totalMethodsNeeded) {
            final String errorMsg = "forgotten password recovery sequence completed " + satisfiedMethods + " methods, " + " but policy requires a total of " + totalMethodsNeeded + " methods";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_RECOVERY_SEQUENCE_INCOMPLETE, errorMsg);
            LOGGER.error(pwmRequest, errorInformation);
            clearForgottenPasswordBean(pwmRequest);
            throw new PwmUnrecoverableException(errorInformation);
        }
    }
    if (!forgottenPasswordBean.getProgress().isAllPassed()) {
        forgottenPasswordBean.getProgress().setAllPassed(true);
        StatisticsManager.incrementStat(pwmRequest, Statistic.RECOVERY_SUCCESSES);
    }
    final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo(pwmRequest, forgottenPasswordBean);
    if (userInfo == null) {
        throw PwmUnrecoverableException.newException(PwmError.ERROR_UNKNOWN, "unable to load userInfo while processing forgotten password controller");
    }
    // check if user's pw is within min lifetime window
    final RecoveryMinLifetimeOption minLifetimeOption = forgottenPasswordProfile.readSettingAsEnum(PwmSetting.RECOVERY_MINIMUM_PASSWORD_LIFETIME_OPTIONS, RecoveryMinLifetimeOption.class);
    if (minLifetimeOption == RecoveryMinLifetimeOption.NONE || (!userInfo.isPasswordLocked() && minLifetimeOption == RecoveryMinLifetimeOption.UNLOCKONLY)) {
        if (userInfo.isWithinPasswordMinimumLifetime()) {
            PasswordUtility.throwPasswordTooSoonException(userInfo, pwmRequest.getSessionLabel());
        }
    }
    final boolean disallowAllButUnlock = minLifetimeOption == RecoveryMinLifetimeOption.UNLOCKONLY && userInfo.isPasswordLocked();
    LOGGER.trace(pwmRequest, "all recovery checks passed, proceeding to configured recovery action");
    final RecoveryAction recoveryAction = ForgottenPasswordUtil.getRecoveryAction(config, forgottenPasswordBean);
    if (recoveryAction == RecoveryAction.SENDNEWPW || recoveryAction == RecoveryAction.SENDNEWPW_AND_EXPIRE) {
        if (disallowAllButUnlock) {
            PasswordUtility.throwPasswordTooSoonException(userInfo, pwmRequest.getSessionLabel());
        }
        ForgottenPasswordUtil.doActionSendNewPassword(pwmRequest);
        return;
    }
    if (forgottenPasswordProfile.readSettingAsBoolean(PwmSetting.RECOVERY_ALLOW_UNLOCK)) {
        final PasswordStatus passwordStatus = userInfo.getPasswordStatus();
        if (!passwordStatus.isExpired() && !passwordStatus.isPreExpired()) {
            if (userInfo.isPasswordLocked()) {
                pwmRequest.setAttribute(PwmRequestAttribute.ForgottenPasswordInhibitPasswordReset, Boolean.TRUE);
                pwmRequest.forwardToJsp(JspUrl.RECOVER_PASSWORD_ACTION_CHOICE);
                return;
            }
        }
    }
    this.executeResetPassword(pwmRequest);
}
Also used : ForgottenPasswordProfile(password.pwm.config.profile.ForgottenPasswordProfile) IdentityVerificationMethod(password.pwm.config.option.IdentityVerificationMethod) PwmApplication(password.pwm.PwmApplication) FormConfiguration(password.pwm.config.value.data.FormConfiguration) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) ActionConfiguration(password.pwm.config.value.data.ActionConfiguration) Configuration(password.pwm.config.Configuration) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) UserInfo(password.pwm.ldap.UserInfo) RecoveryMinLifetimeOption(password.pwm.config.option.RecoveryMinLifetimeOption) ErrorInformation(password.pwm.error.ErrorInformation) RecoveryAction(password.pwm.config.option.RecoveryAction) PasswordStatus(password.pwm.bean.PasswordStatus) ForgottenPasswordBean(password.pwm.http.bean.ForgottenPasswordBean) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 88 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class HelpdeskVerificationStateBean method fromClientString.

static HelpdeskVerificationStateBean fromClientString(final PwmRequest pwmRequest, final String rawValue) throws PwmUnrecoverableException {
    final int maxAgeSeconds = Integer.parseInt(pwmRequest.getConfig().readAppProperty(AppProperty.HELPDESK_VERIFICATION_TIMEOUT_SECONDS));
    final TimeDuration maxAge = new TimeDuration(maxAgeSeconds, TimeUnit.SECONDS);
    final UserIdentity actor = pwmRequest.getUserInfoIfLoggedIn();
    HelpdeskVerificationStateBean state = null;
    if (rawValue != null && !rawValue.isEmpty()) {
        state = pwmRequest.getPwmApplication().getSecureService().decryptObject(rawValue, HelpdeskVerificationStateBean.class);
        if (!state.getActor().equals(actor)) {
            state = null;
        }
    }
    state = state != null ? state : new HelpdeskVerificationStateBean(actor);
    state.maximumAge = maxAge;
    state.purgeOldRecords();
    LOGGER.debug(pwmRequest, "read current state: " + JsonUtil.serialize(state));
    return state;
}
Also used : UserIdentity(password.pwm.bean.UserIdentity) TimeDuration(password.pwm.util.java.TimeDuration)

Example 89 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class NewUserUtils method testIfEntryNameExists.

private static boolean testIfEntryNameExists(final PwmRequest pwmRequest, final String rdnValue) throws PwmUnrecoverableException, ChaiUnavailableException {
    final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().username(rdnValue).build();
    try {
        final Map<UserIdentity, Map<String, String>> results = userSearchEngine.performMultiUserSearch(searchConfiguration, 2, Collections.emptyList(), pwmRequest.getSessionLabel());
        return results != null && !results.isEmpty();
    } catch (PwmOperationalException e) {
        final String msg = "ldap error while searching for duplicate entry names: " + e.getMessage();
        NewUserUtils.LOGGER.error(pwmRequest, msg);
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, msg));
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 90 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class OAuthConsumerServlet method processAction.

@Override
@SuppressWarnings("checkstyle:MethodLength")
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmRequest.getConfig();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final boolean userIsAuthenticated = pwmSession.isAuthenticated();
    final Optional<OAuthRequestState> oAuthRequestState = OAuthMachine.readOAuthRequestState(pwmRequest);
    final OAuthUseCase oAuthUseCaseCase = oAuthRequestState.isPresent() ? oAuthRequestState.get().getoAuthState().getUseCase() : OAuthUseCase.Authentication;
    LOGGER.trace(pwmRequest, "processing oauth return request, useCase=" + oAuthUseCaseCase + ", incoming oAuthRequestState=" + (oAuthRequestState.isPresent() ? JsonUtil.serialize(oAuthRequestState.get()) : "none"));
    // make sure it's okay to be processing this request.
    switch(oAuthUseCaseCase) {
        case Authentication:
            {
                if (!userIsAuthenticated && !pwmSession.getSessionStateBean().isOauthInProgress()) {
                    if (oAuthRequestState.isPresent()) {
                        final String nextUrl = oAuthRequestState.get().getoAuthState().getNextUrl();
                        LOGGER.debug(pwmSession, "received unrecognized oauth response, ignoring authcode and redirecting to embedded next url: " + nextUrl);
                        pwmRequest.sendRedirect(nextUrl);
                        return;
                    }
                    final String errorMsg = "oauth consumer reached, but oauth authentication has not yet been initiated.";
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                    pwmRequest.respondWithError(errorInformation);
                    LOGGER.error(pwmSession, errorMsg);
                    return;
                }
            }
            break;
        default:
            // for non-auth requests its okay to continue
            break;
    }
    // check if there is an "error" on the request sent from the oauth server., if there is then halt.
    {
        final String oauthRequestError = pwmRequest.readParameterAsString("error");
        if (oauthRequestError != null && !oauthRequestError.isEmpty()) {
            final String errorMsg = "incoming request from remote oauth server is indicating an error: " + oauthRequestError;
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg, "Remote Error: " + oauthRequestError, null);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    // check if user is already authenticated - shouldn't be in nominal usage.
    if (userIsAuthenticated) {
        switch(oAuthUseCaseCase) {
            case Authentication:
                LOGGER.debug(pwmSession, "oauth consumer reached, but user is already authenticated; will proceed and verify authcode matches current user identity.");
                break;
            case ForgottenPassword:
                final String errorMsg = "oauth consumer reached via " + OAuthUseCase.ForgottenPassword + ", but user is already authenticated";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                LOGGER.error(pwmSession, errorMsg);
                return;
            default:
                JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
        }
    }
    // mark the inprogress flag to false, if we get this far and fail user needs to start over.
    pwmSession.getSessionStateBean().setOauthInProgress(false);
    if (!oAuthRequestState.isPresent()) {
        final String errorMsg = "state parameter is missing from oauth request";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
        LOGGER.error(pwmSession, errorMsg);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    final OAuthState oauthState = oAuthRequestState.get().getoAuthState();
    final OAuthSettings oAuthSettings = makeOAuthSettings(pwmRequest, oauthState);
    final OAuthMachine oAuthMachine = new OAuthMachine(oAuthSettings);
    // make sure request was initiated in users current session
    if (!oAuthRequestState.get().isSessionMatch()) {
        try {
            switch(oAuthUseCaseCase) {
                case Authentication:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to oauth server for verification update");
                    final String nextURL = oauthState.getNextUrl();
                    oAuthMachine.redirectUserToOAuthServer(pwmRequest, nextURL, null, null);
                    return;
                case ForgottenPassword:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to forgotten password servlet");
                    pwmRequest.sendRedirect(PwmServletDefinition.ForgottenPassword);
                    return;
                default:
                    JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
            }
        } catch (PwmUnrecoverableException e) {
            final String errorMsg = "unexpected error redirecting user to oauth page: " + e.toString();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            setLastError(pwmRequest, errorInformation);
            LOGGER.error(errorInformation.toDebugStr());
        }
    }
    final String requestCodeStr = pwmRequest.readParameterAsString(config.readAppProperty(AppProperty.HTTP_PARAM_OAUTH_CODE));
    LOGGER.trace(pwmSession, "received code from oauth server: " + requestCodeStr);
    final OAuthResolveResults resolveResults;
    try {
        resolveResults = oAuthMachine.makeOAuthResolveRequest(pwmRequest, requestCodeStr);
    } catch (PwmException e) {
        final String errorMsg = "unexpected error communicating with oauth server: " + e.toString();
        final ErrorInformation errorInformation = new ErrorInformation(e.getError(), errorMsg);
        setLastError(pwmRequest, errorInformation);
        LOGGER.error(errorInformation.toDebugStr());
        return;
    }
    if (resolveResults == null || resolveResults.getAccessToken() == null || resolveResults.getAccessToken().isEmpty()) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "browser redirect from oauth server did not include an access token");
        LOGGER.error(pwmRequest, errorInformation);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    if (resolveResults.getExpiresSeconds() > 0) {
        if (resolveResults.getRefreshToken() == null || resolveResults.getRefreshToken().isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "oauth server gave expiration for access token, but did not provide a refresh token");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    final String oauthSuppliedUsername;
    {
        final String getAttributeResponseBodyStr = oAuthMachine.makeOAuthGetAttributeRequest(pwmRequest, resolveResults.getAccessToken());
        final Map<String, String> getAttributeResultValues = JsonUtil.deserializeStringMap(getAttributeResponseBodyStr);
        oauthSuppliedUsername = getAttributeResultValues.get(oAuthSettings.getDnAttributeName());
        if (oauthSuppliedUsername == null || oauthSuppliedUsername.isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "OAuth server did not respond with an username attribute value");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    LOGGER.debug(pwmSession, "received user login id value from OAuth server: " + oauthSuppliedUsername);
    if (oAuthUseCaseCase == OAuthUseCase.ForgottenPassword) {
        redirectToForgottenPasswordServlet(pwmRequest, oauthSuppliedUsername);
        return;
    }
    if (userIsAuthenticated) {
        try {
            final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
            final UserIdentity resolvedIdentity = userSearchEngine.resolveUsername(oauthSuppliedUsername, null, null, pwmSession.getLabel());
            if (resolvedIdentity != null && resolvedIdentity.canonicalEquals(pwmSession.getUserInfo().getUserIdentity(), pwmApplication)) {
                LOGGER.debug(pwmSession, "verified incoming oauth code for already authenticated session does resolve to same as logged in user");
            } else {
                final String errorMsg = "incoming oauth code for already authenticated session does not resolve to same as logged in user ";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                LOGGER.error(pwmSession, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                pwmSession.unauthenticateUser(pwmRequest);
                return;
            }
        } catch (PwmOperationalException e) {
            final String errorMsg = "error while examining incoming oauth code for already authenticated session: " + e.getMessage();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    try {
        if (!userIsAuthenticated) {
            final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.OAUTH);
            sessionAuthenticator.authUserWithUnknownPassword(oauthSuppliedUsername, AuthenticationType.AUTH_WITHOUT_PASSWORD);
        }
        // recycle the session to prevent session fixation attack.
        pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(true);
        // forward to nextUrl
        final String nextUrl = oauthState.getNextUrl();
        LOGGER.debug(pwmSession, "oauth authentication completed, redirecting to originally requested URL: " + nextUrl);
        pwmRequest.sendRedirect(nextUrl);
    } catch (PwmException e) {
        LOGGER.error(pwmSession, "error during OAuth authentication attempt: " + e.getMessage());
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, e.getMessage());
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    LOGGER.trace(pwmSession, "OAuth login sequence successfully completed");
}
Also used : PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmSession(password.pwm.http.PwmSession) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

UserIdentity (password.pwm.bean.UserIdentity)101 ErrorInformation (password.pwm.error.ErrorInformation)62 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)48 PwmOperationalException (password.pwm.error.PwmOperationalException)45 ChaiUser (com.novell.ldapchai.ChaiUser)30 PwmApplication (password.pwm.PwmApplication)27 Map (java.util.Map)21 PwmSession (password.pwm.http.PwmSession)20 UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)19 PwmException (password.pwm.error.PwmException)18 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)17 LinkedHashMap (java.util.LinkedHashMap)17 HelpdeskProfile (password.pwm.config.profile.HelpdeskProfile)17 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)16 Instant (java.time.Instant)16 FormConfiguration (password.pwm.config.value.data.FormConfiguration)16 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)16 ArrayList (java.util.ArrayList)15 UserInfo (password.pwm.ldap.UserInfo)15 RestResultBean (password.pwm.ws.server.RestResultBean)15