Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl.

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:org.silverpeas.core.web.authentication.AuthenticationServlet.java

/**
 * Ask for an authentication for the user behind the incoming HTTP request from a form.
 *
 * @param servletRequest the HTTP request.
 * @param servletResponse the HTTP response.
 * @throws IOException when an error occurs while processing the request or sending the response.
 * @throws javax.servlet.ServletException
 *//*from   w  ww  . j a  v  a  2s.c om*/
@Override
public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    HttpRequest request = HttpRequest.decorate(servletRequest);
    // get an existing session or creates a new one.
    HttpSession session = request.getSession();

    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding(CharEncoding.UTF_8);
    }
    if (request.isWithinAnonymousUserSession()) {
        session.invalidate();
    }

    // Get the authentication settings
    SettingBundle authenticationSettings = ResourceLocator
            .getSettingBundle("org.silverpeas.authentication.settings.authenticationSettings");
    boolean securedAccess = request.isSecure();
    boolean isNewEncryptMode = StringUtil.isDefined(request.getParameter("Var2"));
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(request);
    String domainId = getDomain(request, authenticationParameters, authenticationSettings);
    AuthenticationCredential credential = AuthenticationCredential
            .newWithAsLogin(authenticationParameters.getLogin())
            .withAsPassword(authenticationParameters.getPassword()).withAsDomainId(domainId);

    String authenticationKey = authenticate(request, authenticationParameters, domainId);
    String url = "";

    // Verify if the user can try again to login.
    UserCanTryAgainToLoginVerifier userCanTryAgainToLoginVerifier = AuthenticationUserVerifierFactory
            .getUserCanTryAgainToLoginVerifier(credential);
    userCanTryAgainToLoginVerifier.clearSession(request);

    if (!authService.isInError(authenticationKey)) {

        // Clearing user connection attempt cache.
        userCanTryAgainToLoginVerifier.clearCache();

        if (domainId != null) {
            storeDomain(servletResponse, domainId, securedAccess);
        }
        storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);

        // if required by user, store password in cookie
        storePassword(servletResponse, authenticationParameters.getStoredPassword(), isNewEncryptMode,
                authenticationParameters.getClearPassword(), securedAccess);

        if (request.getAttribute("skipTermsOfServiceAcceptance") == null) {
            UserMustAcceptTermsOfServiceVerifier verifier = AuthenticationUserVerifierFactory
                    .getUserMustAcceptTermsOfServiceVerifier(credential);
            try {
                verifier.verify();
            } catch (AuthenticationUserMustAcceptTermsOfService authenticationUserMustAcceptTermsOfService) {
                forward(request, servletResponse, verifier.getDestination(request));
                return;
            }
        }

        if (mandatoryQuestionChecker.check(request, authenticationKey)) {
            forward(request, servletResponse, mandatoryQuestionChecker.getDestination());
            return;
        }

        String absoluteUrl = silverpeasSessionOpener.openSession(request, authenticationKey);
        // fetch the new opened session
        session = request.getSession(false);
        session.setAttribute("Silverpeas_pwdForHyperlink", authenticationParameters.getClearPassword());
        writeSessionCookie(servletResponse, session, securedAccess);
        servletResponse.sendRedirect(servletResponse.encodeRedirectURL(absoluteUrl));
        return;
    }
    // Authentication failed : remove password from cookies to avoid infinite loop
    removeStoredPassword(servletResponse, securedAccess);
    if (authenticationParameters.isCasMode()) {
        url = "/admin/jsp/casAuthenticationError.jsp";
    } else {
        if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)
                || AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
            try {
                if (userCanTryAgainToLoginVerifier.isActivated()) {
                    storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                            securedAccess);
                    storeDomain(servletResponse, domainId, securedAccess);
                }
                if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)) {
                    url = userCanTryAgainToLoginVerifier.verify().performRequestUrl(request,
                            "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD);
                } else if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
                    url = userCanTryAgainToLoginVerifier.verify().performRequestUrl(request,
                            "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD_DOMAIN);
                }
            } catch (AuthenticationNoMoreUserConnectionAttemptException e) {
                url = userCanTryAgainToLoginVerifier.getErrorDestination();
            }
        } else if (UserCanLoginVerifier.ERROR_USER_ACCOUNT_BLOCKED.equals(authenticationKey)
                || UserCanLoginVerifier.ERROR_USER_ACCOUNT_DEACTIVATED.equals(authenticationKey)) {
            if (userCanTryAgainToLoginVerifier.isActivated()
                    || StringUtil.isDefined(userCanTryAgainToLoginVerifier.getUser().getId())) {
                // If user can try again to login verifier is activated or if the user has been found
                // from credential, the login and the domain are stored
                storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                        securedAccess);
                storeDomain(servletResponse, domainId, securedAccess);
                url = AuthenticationUserVerifierFactory
                        .getUserCanLoginVerifier(userCanTryAgainToLoginVerifier.getUser())
                        .getErrorDestination();
            } else {
                if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD.equals(authenticationKey)) {
                    url = "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD;
                } else if (AuthenticationService.ERROR_INCORRECT_LOGIN_PWD_DOMAIN.equals(authenticationKey)) {
                    url = "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD_DOMAIN;
                }
            }
        } else if (AuthenticationService.ERROR_PWD_EXPIRED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                SettingBundle settings = ResourceLocator
                        .getSettingBundle("org.silverpeas.authentication.settings.passwordExpiration");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (AuthenticationService.ERROR_PWD_MUST_BE_CHANGED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                SettingBundle settings = ResourceLocator
                        .getSettingBundle("org.silverpeas.authentication.settings.passwordExpiration");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (UserMustChangePasswordVerifier.ERROR_PWD_MUST_BE_CHANGED_ON_FIRST_LOGIN
                .equals(authenticationKey)) {
            // User has been successfully authenticated, but he has to change his password on his
            // first login and login / domain id can be stored
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            storeDomain(servletResponse, domainId, securedAccess);
            url = AuthenticationUserVerifierFactory.getUserMustChangePasswordVerifier(credential)
                    .getDestinationOnFirstLogin(request);
            forward(request, servletResponse, url);
            return;
        } else if (authenticationParameters.isSsoMode()) {
            // User has been successfully authenticated on AD, but he has no user account on Silverpeas
            // -> login / domain id can be stored
            storeDomain(servletResponse, domainId, securedAccess);
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            url = "/Login.jsp?ErrorCode=" + SSO_UNEXISTANT_USER_ACCOUNT;
        } else {
            url = "/Login.jsp?ErrorCode=" + TECHNICAL_ISSUE;
        }
    }
    servletResponse
            .sendRedirect(servletResponse.encodeRedirectURL(URLUtil.getFullApplicationURL(request) + url));
}

From source file:org.etudes.mneme.tool.EnterView.java

/**
 * Redirect to the appropriate question screen for this submission
 * // w  w  w. j  a v a  2 s .c  o m
 * @param req
 *        Servlet request.
 * @param res
 *        Servlet response.
 * @param submission
 *        The submission.
 * @param toc
 *        if true, send to TOC if possible (not possible for linear).
 * @param instructions
 *        if true, send to section instructions for first question.
 * @param returnDestination
 *        The final return destination path.
 */
protected void redirectToQuestion(HttpServletRequest req, HttpServletResponse res, Submission submission,
        boolean toc, boolean instructions, String returnDestination) throws IOException {
    String destination = null;
    Assessment assessment = submission.getAssessment();

    // if we are random access, and allowed, and more than a single question, send to TOC
    if (toc && assessment.getRandomAccess() && !assessment.getIsSingleQuestion()) {
        destination = "/toc/" + submission.getId() + returnDestination;
    }

    else {
        // find the first incomplete question
        Question question = submission.getFirstIncompleteQuestion();

        // if not found, and we have only one, go there
        if ((question == null) && (assessment.getIsSingleQuestion())) {
            question = submission.getFirstQuestion();
        }

        // if we don't have one, we will go to the toc (or final_review for linear)
        if (question == null) {
            if (!assessment.getRandomAccess()) {
                destination = "/final_review/" + submission.getId() + returnDestination;
            } else {
                destination = "/toc/" + submission.getId() + returnDestination;
            }
        }

        else {
            // send to the section instructions if it's a first question and by-question
            // and we are showing part presentation and we have something authored for this part
            if (instructions && (question.getPartOrdering().getIsFirst())
                    && (assessment.getParts().getShowPresentation())
                    && (!question.getPart().getPresentation().getIsEmpty())
                    && (assessment.getQuestionGrouping() == QuestionGrouping.question)) {
                // to instructions
                destination = "/part_instructions/" + submission.getId() + "/" + question.getPart().getId()
                        + returnDestination;
            }

            // or to the question
            else {
                if (assessment.getQuestionGrouping() == QuestionGrouping.question) {
                    destination = "/question/" + submission.getId() + "/q" + question.getId() + "/-"
                            + returnDestination;
                } else if (assessment.getQuestionGrouping() == QuestionGrouping.part) {
                    destination = "/question/" + submission.getId() + "/p" + question.getPart().getId();

                    // include the question target if not the first question in the section
                    if (!question.getPartOrdering().getIsFirst()) {
                        destination = destination + "/" + question.getId();
                    } else {
                        destination = destination + "/-";
                    }

                    destination = destination + returnDestination;
                } else {
                    destination = "/question/" + submission.getId() + "/a";

                    // include the question target if not the first question in the assessment
                    if (!question.getAssessmentOrdering().getIsFirst().booleanValue()) {
                        destination = destination + "/" + question.getId();
                    } else {
                        destination = destination + "/-";
                    }

                    destination = destination + returnDestination;
                }
            }
        }
    }

    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
    return;
}

From source file:org.josso.gl2.agent.SSOAgentValve.java

private void securityCheck(HttpServletRequest hreq, HttpServletResponse hres, SingleSignOnEntry entry,
        SSOPartnerAppConfig cfg, String phase) {
    String ssoId = entry.ssoId;/*from w  w  w . j  a v  a 2 s  .  com*/
    try {
        cookie = _agent.newJossoCookie(hreq.getContextPath(), ssoId);
        hres.addCookie(cookie);
    } catch (Exception e) {
        log(phase + " Pas de bras pas de chocolat !", e);
    }
    jossoSessionId = ssoId;
    //T10-3
    //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
    String requestURI = getSavedSplashResource(session.getSession());
    if (requestURI == null) {
        requestURI = getSavedRequestURL(session);
        if (requestURI == null) {

            if (cfg.getDefaultResource() != null) {
                requestURI = cfg.getDefaultResource();
            } else {
                // If no saved request is found, redirect to the partner app root :
                requestURI = hreq.getRequestURI().substring(0,
                        (hreq.getRequestURI().length() - _agent.getJOSSOSecurityCheckUri().length()));
            }

            // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
            String singlePointOfAccess = _agent.getSinglePointOfAccess();
            if (singlePointOfAccess != null) {
                requestURI = singlePointOfAccess + requestURI;
            } else {
                String reverseProxyHost = hreq
                        .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                if (reverseProxyHost != null) {
                    requestURI = reverseProxyHost + requestURI;
                }
            }

            if (debug >= 1)
                log(phase + "-3 No saved request found, using : '" + requestURI + "'");
        }
    }

    clearSavedRequestURLs(session);
    _agent.clearAutomaticLoginReferer(hreq);
    _agent.prepareNonCacheResponse(hres);
    //T10-4
    // Check if we have a post login resource :
    String postAuthURI = cfg.getPostAuthenticationResource();
    try {
        if (postAuthURI != null) {
            String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
            if (debug >= 1) {
                log(phase + "-4 Redirecting to post-auth-resource '" + postAuthURL + "'");

            }
            hres.sendRedirect(postAuthURL);
        } else {
            if (debug >= 1) {
                log(phase + "-4 Redirecting to original '" + requestURI + "'");

            }
            hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            //on garde des fois que ...
            theOriginal = hres.encodeRedirectURL(requestURI);
        }
    } catch (IOException iOException) {
        log(phase + " Erreur redirection", iOException);
    }
    _agent.addEntrySSOIDsuccessed(ssoId, entry.getPrincipal().getName());
    log(phase + " Fin josso_check jossoSessionId=" + jossoSessionId);
    //c'est pas fini et pas en erreur pourtant ...

}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Ask for an authentication for the user behind the incoming HTTP request from a form.
 *
 * @param servletRequest the HTTP request.
 * @param servletResponse the HTTP response.
 * @throws IOException when an error occurs while processing the request or sending the response.
 * @throws javax.servlet.ServletException
 *///  ww  w. jav a 2 s.  c o  m
@Override
public void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    HttpRequest request = HttpRequest.decorate(servletRequest);
    // get an existing session or creates a new one.
    HttpSession session = request.getSession();

    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding(CharEncoding.UTF_8);
    }
    if (request.isWithinAnonymousUserSession()) {
        silverpeasSessionOpener.closeSession(session);
    }

    // Get the authentication settings
    ResourceLocator authenticationSettings = new ResourceLocator(
            "org.silverpeas.authentication.settings.authenticationSettings", "");
    boolean securedAccess = request.isSecure();
    boolean isNewEncryptMode = StringUtil.isDefined(request.getParameter("Var2"));
    AuthenticationParameters authenticationParameters = new AuthenticationParameters(request);
    String domainId = getDomain(request, authenticationParameters, authenticationSettings);
    AuthenticationCredential credential = AuthenticationCredential
            .newWithAsLogin(authenticationParameters.getLogin())
            .withAsPassword(authenticationParameters.getPassword()).withAsDomainId(domainId);

    String authenticationKey = authenticate(request, authenticationParameters, domainId);
    String url;

    // Verify if the user can try again to login.
    UserCanTryAgainToLoginVerifier userCanTryAgainToLoginVerifier = AuthenticationUserVerifierFactory
            .getUserCanTryAgainToLoginVerifier(credential);
    userCanTryAgainToLoginVerifier.clearSession(request);

    if (!authService.isInError(authenticationKey)) {

        // Clearing user connection attempt cache.
        userCanTryAgainToLoginVerifier.clearCache();

        if (domainId != null) {
            storeDomain(servletResponse, domainId, securedAccess);
        }
        storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);

        // if required by user, store password in cookie
        storePassword(servletResponse, authenticationParameters.getStoredPassword(), isNewEncryptMode,
                authenticationParameters.getClearPassword(), securedAccess);

        if (request.getAttribute("skipTermsOfServiceAcceptance") == null) {
            UserMustAcceptTermsOfServiceVerifier verifier = AuthenticationUserVerifierFactory
                    .getUserMustAcceptTermsOfServiceVerifier(credential);
            try {
                verifier.verify();
            } catch (AuthenticationUserMustAcceptTermsOfService authenticationUserMustAcceptTermsOfService) {
                forward(request, servletResponse, verifier.getDestination(request));
                return;
            }
        }

        MandatoryQuestionChecker checker = new MandatoryQuestionChecker();
        if (checker.check(request, authenticationKey)) {
            forward(request, servletResponse, checker.getDestination());
            return;
        }

        String absoluteUrl = silverpeasSessionOpener.openSession(request, authenticationKey);
        // fetch the new opened session
        session = request.getSession(false);
        session.setAttribute("Silverpeas_pwdForHyperlink", authenticationParameters.getClearPassword());
        writeSessionCookie(servletResponse, session, securedAccess);
        servletResponse.sendRedirect(servletResponse.encodeRedirectURL(absoluteUrl));
        return;
    }
    // Authentication failed : remove password from cookies to avoid infinite loop
    removeStoredPassword(servletResponse, securedAccess);
    if (authenticationParameters.isCasMode()) {
        url = "/admin/jsp/casAuthenticationError.jsp";
    } else {
        if ("Error_1".equals(authenticationKey)) {
            try {
                if (userCanTryAgainToLoginVerifier.isActivated()) {
                    storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                            securedAccess);
                    storeDomain(servletResponse, domainId, securedAccess);
                }
                url = userCanTryAgainToLoginVerifier.verify().performRequestUrl(request,
                        "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD);
            } catch (AuthenticationNoMoreUserConnectionAttemptException e) {
                url = userCanTryAgainToLoginVerifier.getErrorDestination();
            }
        } else if (AuthenticationService.ERROR_PWD_EXPIRED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                ResourceLocator settings = new ResourceLocator(
                        "com.silverpeas.authentication.settings.passwordExpiration", "");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (AuthenticationService.ERROR_PWD_MUST_BE_CHANGED.equals(authenticationKey)) {
            String allowPasswordChange = (String) session.getAttribute(Authentication.PASSWORD_CHANGE_ALLOWED);
            if (StringUtil.getBooleanValue(allowPasswordChange)) {
                ResourceLocator settings = new ResourceLocator(
                        "com.silverpeas.authentication.settings.passwordExpiration", "");
                url = settings.getString("passwordExpiredURL") + "?login=" + authenticationParameters.getLogin()
                        + "&domainId=" + domainId;
            } else {
                url = "/Login.jsp?ErrorCode=" + AuthenticationService.ERROR_PWD_EXPIRED;
            }
        } else if (UserMustChangePasswordVerifier.ERROR_PWD_MUST_BE_CHANGED_ON_FIRST_LOGIN
                .equals(authenticationKey)) {
            // User has been successfully authenticated, but he has to change his password on his
            // first login and login / domain id can be stored
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            storeDomain(servletResponse, domainId, securedAccess);
            url = AuthenticationUserVerifierFactory.getUserMustChangePasswordVerifier(credential)
                    .getDestinationOnFirstLogin(request);
            forward(request, servletResponse, url);
            return;
        } else if (UserCanLoginVerifier.ERROR_USER_ACCOUNT_BLOCKED.equals(authenticationKey)) {
            if (userCanTryAgainToLoginVerifier.isActivated()
                    || StringUtil.isDefined(userCanTryAgainToLoginVerifier.getUser().getId())) {
                // If user can try again to login verifier is activated or if the user has been found
                // from credential, the login and the domain are stored
                storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(),
                        securedAccess);
                storeDomain(servletResponse, domainId, securedAccess);
                url = AuthenticationUserVerifierFactory.getUserCanLoginVerifier((UserDetail) null)
                        .getErrorDestination();
            } else {
                url = "/Login.jsp?ErrorCode=" + INCORRECT_LOGIN_PWD;
            }
        } else if (authenticationParameters.isSsoMode()) {
            // User has been successfully authenticated on AD, but he has no user account on Silverpeas
            // -> login / domain id can be stored
            storeDomain(servletResponse, domainId, securedAccess);
            storeLogin(servletResponse, isNewEncryptMode, authenticationParameters.getLogin(), securedAccess);
            url = "/Login.jsp?ErrorCode=" + SSO_UNEXISTANT_USER_ACCOUNT;
        } else {
            url = "/Login.jsp?ErrorCode=" + TECHNICAL_ISSUE;
        }
    }
    servletResponse
            .sendRedirect(servletResponse.encodeRedirectURL(URLManager.getFullApplicationURL(request) + url));
}

From source file:org.dspace.app.webui.search.LuceneSearchRequestProcessor.java

/**
 * <p>//w w  w .ja v  a2s  .  co m
 * All metadata is search for the value contained in the "query" parameter.
 * If the "location" parameter is present, the user's location is switched
 * to that location using a redirect. Otherwise, the user's current location
 * is used to constrain the query; i.e., if the user is "in" a collection,
 * only results from the collection will be returned.
 * <p>
 * The value of the "location" parameter should be ALL (which means no
 * location), a the ID of a community (e.g. "123"), or a community ID, then
 * a slash, then a collection ID, e.g. "123/456".
 * 
 * author: Robert Tansley
 */
@Override
public void doSimpleSearch(Context context, HttpServletRequest request, HttpServletResponse response)
        throws SearchProcessorException, IOException, ServletException {
    try {
        // Get the query
        String query = request.getParameter("query");
        int start = UIUtil.getIntParameter(request, "start");
        String advanced = request.getParameter("advanced");
        String fromAdvanced = request.getParameter("from_advanced");
        int sortBy = UIUtil.getIntParameter(request, "sort_by");
        String order = request.getParameter("order");
        int rpp = UIUtil.getIntParameter(request, "rpp");
        String advancedQuery = "";

        // can't start earlier than 0 in the results!
        if (start < 0) {
            start = 0;
        }

        int collCount = 0;
        int commCount = 0;
        int itemCount = 0;

        Item[] resultsItems;
        Collection[] resultsCollections;
        Community[] resultsCommunities;

        QueryResults qResults = null;
        QueryArgs qArgs = new QueryArgs();
        SortOption sortOption = null;

        if (request.getParameter("etal") != null) {
            qArgs.setEtAl(UIUtil.getIntParameter(request, "etal"));
        }

        try {
            if (sortBy > 0) {
                sortOption = SortOption.getSortOption(sortBy);
                qArgs.setSortOption(sortOption);
            }

            if (SortOption.ASCENDING.equalsIgnoreCase(order)) {
                qArgs.setSortOrder(SortOption.ASCENDING);
            } else {
                qArgs.setSortOrder(SortOption.DESCENDING);
            }
        } catch (Exception e) {
        }

        // Override the page setting if exporting metadata
        if ("submit_export_metadata".equals(UIUtil.getSubmitButton(request, "submit"))) {
            qArgs.setPageSize(Integer.MAX_VALUE);
        } else if (rpp > 0) {
            qArgs.setPageSize(rpp);
        }

        // if the "advanced" flag is set, build the query string from the
        // multiple query fields
        if (advanced != null) {
            query = qArgs.buildQuery(request);
            advancedQuery = qArgs.buildHTTPQuery(request);
        }

        // Ensure the query is non-null
        if (query == null) {
            query = "";
        }

        // Get the location parameter, if any
        String location = request.getParameter("location");

        // If there is a location parameter, we should redirect to
        // do the search with the correct location.
        if ((location != null) && !location.equals("")) {
            String url = "";

            if (!location.equals("/")) {
                // Location is a Handle
                url = "/handle/" + location;
            }

            // Encode the query
            query = URLEncoder.encode(query, Constants.DEFAULT_ENCODING);

            if (advancedQuery.length() > 0) {
                query = query + "&from_advanced=true&" + advancedQuery;
            }

            // Do the redirect
            response.sendRedirect(response
                    .encodeRedirectURL(request.getContextPath() + url + "/simple-search?query=" + query));

            return;
        }

        // Build log information
        String logInfo = "";

        // Get our location
        Community community = UIUtil.getCommunityLocation(request);
        Collection collection = UIUtil.getCollectionLocation(request);

        // get the start of the query results page
        //        List resultObjects = null;
        qArgs.setQuery(query);
        qArgs.setStart(start);

        // Perform the search
        if (collection != null) {
            logInfo = "collection_id=" + collection.getID() + ",";

            // Values for drop-down box
            request.setAttribute("community", community);
            request.setAttribute("collection", collection);

            qResults = DSQuery.doQuery(context, qArgs, collection);
        } else if (community != null) {
            logInfo = "community_id=" + community.getID() + ",";

            request.setAttribute("community", community);

            // Get the collections within the community for the dropdown box
            request.setAttribute("collection.array", community.getCollections());

            qResults = DSQuery.doQuery(context, qArgs, community);
        } else {
            // Get all communities for dropdown box
            Community[] communities = Community.findAll(context);
            request.setAttribute("community.array", communities);

            qResults = DSQuery.doQuery(context, qArgs);
        }

        // now instantiate the results and put them in their buckets
        for (int i = 0; i < qResults.getHitTypes().size(); i++) {
            Integer myType = qResults.getHitTypes().get(i);

            // add the handle to the appropriate lists
            switch (myType.intValue()) {
            case Constants.ITEM:
                itemCount++;
                break;

            case Constants.COLLECTION:
                collCount++;
                break;

            case Constants.COMMUNITY:
                commCount++;
                break;
            }
        }

        // Make objects from the handles - make arrays, fill them out
        resultsCommunities = new Community[commCount];
        resultsCollections = new Collection[collCount];
        resultsItems = new Item[itemCount];

        collCount = 0;
        commCount = 0;
        itemCount = 0;

        for (int i = 0; i < qResults.getHitTypes().size(); i++) {
            Integer myId = qResults.getHitIds().get(i);
            String myHandle = qResults.getHitHandles().get(i);
            Integer myType = qResults.getHitTypes().get(i);

            // add the handle to the appropriate lists
            switch (myType.intValue()) {
            case Constants.ITEM:
                if (myId != null) {
                    resultsItems[itemCount] = Item.find(context, myId);
                } else {
                    resultsItems[itemCount] = (Item) HandleManager.resolveToObject(context, myHandle);
                }

                if (resultsItems[itemCount] == null) {
                    throw new SQLException("Query \"" + query + "\" returned unresolvable item");
                }
                itemCount++;
                break;

            case Constants.COLLECTION:
                if (myId != null) {
                    resultsCollections[collCount] = Collection.find(context, myId);
                } else {
                    resultsCollections[collCount] = (Collection) HandleManager.resolveToObject(context,
                            myHandle);
                }

                if (resultsCollections[collCount] == null) {
                    throw new SQLException("Query \"" + query + "\" returned unresolvable collection");
                }

                collCount++;
                break;

            case Constants.COMMUNITY:
                if (myId != null) {
                    resultsCommunities[commCount] = Community.find(context, myId);
                } else {
                    resultsCommunities[commCount] = (Community) HandleManager.resolveToObject(context,
                            myHandle);
                }

                if (resultsCommunities[commCount] == null) {
                    throw new SQLException("Query \"" + query + "\" returned unresolvable community");
                }

                commCount++;
                break;
            }
        }

        // Log
        log.info(LogManager.getHeader(context, "search",
                logInfo + "query=\"" + query + "\",results=(" + resultsCommunities.length + ","
                        + resultsCollections.length + "," + resultsItems.length + ")"));

        // Pass in some page qualities
        // total number of pages
        int pageTotal = 1 + ((qResults.getHitCount() - 1) / qResults.getPageSize());

        // current page being displayed
        int pageCurrent = 1 + (qResults.getStart() / qResults.getPageSize());

        // pageLast = min(pageCurrent+9,pageTotal)
        int pageLast = ((pageCurrent + 9) > pageTotal) ? pageTotal : (pageCurrent + 9);

        // pageFirst = max(1,pageCurrent-9)
        int pageFirst = ((pageCurrent - 9) > 1) ? (pageCurrent - 9) : 1;

        //Fire an event to log our search
        DSpaceObject scope = null;
        if (collection != null) {
            scope = collection;
        } else if (community != null) {
            scope = community;
        }
        logSearch(context, request, query, pageCurrent, scope);

        // Pass the results to the display JSP
        request.setAttribute("items", resultsItems);
        request.setAttribute("communities", resultsCommunities);
        request.setAttribute("collections", resultsCollections);

        request.setAttribute("pagetotal", Integer.valueOf(pageTotal));
        request.setAttribute("pagecurrent", Integer.valueOf(pageCurrent));
        request.setAttribute("pagelast", Integer.valueOf(pageLast));
        request.setAttribute("pagefirst", Integer.valueOf(pageFirst));

        request.setAttribute("queryresults", qResults);

        // And the original query string
        request.setAttribute("query", query);

        request.setAttribute("order", qArgs.getSortOrder());
        request.setAttribute("sortedBy", sortOption);

        if (AuthorizeManager.isAdmin(context)) {
            // Set a variable to create admin buttons
            request.setAttribute("admin_button", Boolean.TRUE);
        }

        if ((fromAdvanced != null) && (qResults.getHitCount() == 0)) {
            // send back to advanced form if no results
            Community[] communities = Community.findAll(context);
            request.setAttribute("communities", communities);
            request.setAttribute("no_results", "yes");

            Map<String, String> queryHash = qArgs.buildQueryMap(request);

            if (queryHash != null) {
                for (Map.Entry<String, String> entry : queryHash.entrySet()) {
                    request.setAttribute(entry.getKey(), entry.getValue());
                }
            }

            JSPManager.showJSP(request, response, "/search/advanced.jsp");
        } else if ("submit_export_metadata".equals(UIUtil.getSubmitButton(request, "submit"))) {
            exportMetadata(context, response, resultsItems);
        } else {
            JSPManager.showJSP(request, response, "/search/results.jsp");
        }
    } catch (IllegalStateException e) {
        throw new SearchProcessorException(e.getMessage(), e);
    } catch (SQLException e) {
        throw new SearchProcessorException(e.getMessage(), e);
    }
}

From source file:org.etudes.mneme.tool.QuestionView.java

/**
 * Redirect to the appropriate question screen for this submission
 * /*ww  w  . j a  v a 2 s . co m*/
 * @param req
 *        Servlet request.
 * @param res
 *        Servlet response.
 * @param submission
 *        The submission.
 * @param toc
 *        if true, send to TOC if possible (not possible for linear).
 * @param instructions
 *        if true, send to part instructions for first question.
 * @param returnDestination
 *        The final return destination path.
 */
protected void redirectToQuestion(HttpServletRequest req, HttpServletResponse res, Submission submission,
        boolean toc, boolean instructions, String returnDestination) throws IOException {
    String destination = null;
    Assessment assessment = submission.getAssessment();

    // if we are random access, and not a single question, and allowed, send to TOC
    if (toc && assessment.getRandomAccess() && !assessment.getIsSingleQuestion()) {
        destination = "/toc/" + submission.getId() + returnDestination;
    }

    else {
        // find the first incomplete question
        Question question = submission.getFirstIncompleteQuestion();

        // if not found, and we have only one, go there
        if ((question == null) && (assessment.getIsSingleQuestion())) {
            question = submission.getFirstQuestion();
        }

        // if we don't have one, we will go to the toc (or final_review for linear)
        if (question == null) {
            if (!assessment.getRandomAccess()) {
                destination = "/final_review/" + submission.getId() + returnDestination;
            } else {
                destination = "/toc/" + submission.getId() + returnDestination;
            }
        }

        else {
            // send to the part instructions if it's a first question and by-question
            if (instructions && (question.getPartOrdering().getIsFirst())
                    && (assessment.getParts().getShowPresentation())
                    && (assessment.getQuestionGrouping() == QuestionGrouping.question)) {
                // to instructions
                destination = "/part_instructions/" + submission.getId() + "/" + question.getPart().getId()
                        + returnDestination;
            }

            // or to the question
            else {
                if (assessment.getQuestionGrouping() == QuestionGrouping.question) {
                    destination = "/question/" + submission.getId() + "/q" + question.getId() + "/-"
                            + returnDestination;
                } else if (assessment.getQuestionGrouping() == QuestionGrouping.part) {
                    destination = "/question/" + submission.getId() + "/p" + question.getPart().getId();

                    // include the question target if not the first question in the part
                    if (!question.getPartOrdering().getIsFirst()) {
                        destination = destination + "/" + question.getId();
                    } else {
                        destination = destination + "/-";
                    }

                    destination = destination + returnDestination;
                } else {
                    destination = "/question/" + submission.getId() + "/a";

                    // include the question target if not the first question in the assessment
                    if (!question.getAssessmentOrdering().getIsFirst()) {
                        destination = destination + "/" + question.getId();
                    } else {
                        destination = destination + "/-";
                    }

                    destination = destination + returnDestination;
                }
            }
        }
    }

    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
    return;
}

From source file:org.openanzo.servlet.EncryptedTokenAuthenticator.java

/**
 * Perform form authentication. Called from SecurityHandler.
 * /*from   w  w w  .j  a  v  a 2s  .  co  m*/
 * @param servletRequest
 *            request to authenticate
 * @param response
 *            response to send response data
 * 
 * @return UserPrincipal if authenticated else null.
 * @throws IOException
 */
@SuppressWarnings("null")
public boolean authenticate(HttpServletRequest servletRequest, HttpServletResponse response)
        throws IOException {
    // NOTE: Jetty will sometimes call this method with a null response parameter. In particular, from
    // the org.eclipse.jetty.Request#getUserPrincipal() method.
    boolean ret = false;
    Request request = Request.getRequest(servletRequest);
    String uri = request.getServletPath();
    boolean protectedPath = false;
    for (PathSpec spec : protectedPathSpec) {
        if (spec.matches(uri)) {
            protectedPath = true;
            break;
        }
    }
    // Setup some defaults. Unfortunately, this is the only place we really get to set these up since the
    // Authenticator interface doesn't have an 'init'-like method.
    if (tokenTimeout <= 0) {
        tokenTimeout = 30 * DateUtils.MILLIS_PER_MINUTE;
    }
    if (tokenRefreshWindow <= 0) {
        tokenRefreshWindow = 5 * DateUtils.MILLIS_PER_MINUTE;
    }
    if (customTokenRefresh == null) {
        customTokenRefresh = Boolean.FALSE;
    }

    // Now handle the request
    uri = request.getPathInfo();
    if (uri.endsWith(LOGIN_URI_SUFFIX)) {
        // Handle a request for authentication.

        ret = false; // We will entirely handle the request here so return false to stop processing the request.

        String username = request.getParameter(USERNAME_PARAMETER_NAME);
        String password = request.getParameter(PASSWORD_PARAMETER_NAME);

        if (username == null || password == null) {
            log.error(LogUtils.SECURITY_MARKER,
                    "Invalid anzo_authenticate request url:{} username:{} password:{}",
                    new Object[] { uri, username, password == null ? null : "XXXObscuredNonNullPasswordXXX" });
        }

        AnzoPrincipal userPrincipal = null;
        try {
            userPrincipal = realm.authenticate(username, password, request);
        } catch (Exception e) {
            // No matter what sort of failure occurs in the realm we want to make sure to send the  appropriate
            // error response or redirect. So we can't all exceptions here.
            log.debug(LogUtils.SECURITY_MARKER, "Failed authentication call to the realm.", e);
        }
        if (userPrincipal == null) {
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Authentication request FAILED for {}",
                        StringUtil.printable(username));
            }
            request.setAuthentication(null);

            if (response != null) {
                if (_formErrorPage == null || isRequestSentByXmlHttpRequest(request)) {
                    if (log.isDebugEnabled()) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending 403 Forbidden error due to invalid credentials for user {}", username);
                    }
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    String redirectPath = response
                            .encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage));
                    log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form error page {}", redirectPath);
                    response.setContentLength(0);
                    response.sendRedirect(redirectPath);
                }
            }
        } else {
            // Authenticated OK
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Authentication request OK for {}",
                        StringUtil.printable(username));
            }
            request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD));

            // Set the encrypted token
            if (response != null) {
                try {
                    String token = createEncryptedToken(username, request.getRemoteAddr());
                    Cookie tokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, token);
                    tokenCookie.setPath("/");
                    response.addCookie(tokenCookie);
                    if (isRequestSentByXmlHttpRequest(request)) {
                        // XMLHttpRequests just want a response with the cookie, no fancy redirects or anything like that.
                        // just send back 200 in text.(Need to send back something else firefox reports an error)
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.setContentType("text/plain");
                        PrintWriter out = response.getWriter();
                        out.print(HttpServletResponse.SC_OK);
                        out.flush();
                        out.close();
                    } else {
                        // Redirect to the URL to user wanted to get to initially, or "/" if there isn't any such URL.
                        // We get the URL from a query parameter in the HTTP Referer (sic) header.
                        String referer = request.getHeader(HttpHeaders.REFERER);
                        String redirectPath = null;
                        if (referer != null) {
                            HttpURI refererUri = new HttpURI(referer);
                            MultiMap<String> queryParams = new MultiMap<String>();
                            refererUri.decodeQueryTo(queryParams, null);
                            String desiredUrl = (String) queryParams.getValue(ANZO_URL_QUERY_PARAM, 0);
                            if (desiredUrl != null) {
                                redirectPath = desiredUrl;
                            }
                        }
                        if (redirectPath == null) {
                            redirectPath = URIUtil.addPaths(request.getContextPath(), "/");
                        }
                        redirectPath = response.encodeRedirectURL(redirectPath);
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending redirect to root {} after successful login request.", redirectPath);
                        response.sendRedirect(redirectPath);
                    }

                } catch (AnzoException cause) {
                    IOException ex = new IOException("Error creating encrypted authentication token.");
                    ex.initCause(cause);
                    throw ex;
                }
            }
        }

    } else if (isLoginOrErrorPage(uri)) {
        // Don't authenticate authform or errorpage. Just let the system them out.
        ret = true;
    } else if (protectedPath) {
        // This is a regular request for a protected resource, so check whether there is a valid
        // encrypted token in the request.
        AnzoPrincipal userPrincipal = null;

        // Parse and validate the authentication token from the cookie
        Token token = null;
        long currentTime = System.currentTimeMillis();
        Cookie[] cookies = request.getCookies();
        Cookie tokenCookie = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (ANZO_TOKEN_COOKIE_NAME.equals(cookieName)) {
                    tokenCookie = cookie;
                    try {
                        token = parseAnzoToken(cookie.getValue());
                        userPrincipal = validateAuthToken(token, realm, request.getRemoteAddr(), currentTime);
                    } catch (AnzoException e) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Error decrypting and parsing authentication token.", e);
                    }
                    break;
                }
            }
        }

        if (userPrincipal == null) {
            // Invalid, expired, or non-existent token
            ret = false; // Don't serve the resource

            if (log.isDebugEnabled()) {
                String msg = "Auth token ";
                if (tokenCookie == null) {
                    msg += "MISSING";
                } else {
                    msg += "INVALID";
                }
                log.debug(LogUtils.SECURITY_MARKER, msg + " for URL: {}",
                        StringUtil.printable(request.getRequestURI()));
            }
            if (response != null) {
                Cookie cookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, "");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie); // adding a cookie with MaxAge=0 tells the client to delete the cookie.
                if (_formLoginPage == null || isRequestSentByXmlHttpRequest(request)) {
                    if (log.isDebugEnabled()) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending 403 Forbidden error due to invalid auth token. Token: {}", token);
                    }
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // We save the URL the user tried to access into a query parameter in the redirect to the login page.
                    // That way the login page can send the user to the page they wanted after they finish logging in.
                    // First we must reconstruct the URL the user accessed.
                    String requestUrl = uri;
                    if (request.getQueryString() != null) {
                        requestUrl += "?" + request.getQueryString();
                    }
                    requestUrl = request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + URIUtil.addPaths(request.getContextPath(), requestUrl);
                    // Now we add the requested URL as a query parameter to the login URL
                    MultiMap<String> loginPageUrlQueryParams = new MultiMap<String>();
                    loginPageUrlQueryParams.put(ANZO_URL_QUERY_PARAM, requestUrl);
                    String loginPageUrl = URIUtil.addPaths(request.getContextPath(), _formLoginPage);
                    try {
                        loginPageUrl = addQueryParametersToURI(loginPageUrl, loginPageUrlQueryParams);
                    } catch (URISyntaxException e) {
                        log.warn(LogUtils.SECURITY_MARKER,
                                "Error creating login redirect URL. The user's attempted URL won't be saved for use after login.",
                                e);
                    }
                    String redirectPath = response.encodeRedirectURL(loginPageUrl);
                    log.debug(LogUtils.SECURITY_MARKER,
                            "Sending redirect to form login page {} after request without adequate credentials.",
                            redirectPath);
                    response.setContentLength(0);
                    response.sendRedirect(redirectPath);
                }
            }
        } else {
            // Properly authenticated
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Auth token OK for '{}' for URL:{}",
                        StringUtil.printable(userPrincipal.getName()),
                        StringUtil.printable(request.getRequestURI()));
            }
            if (userPrincipal instanceof AnzoPrincipal) {
                request.setAttribute(SerializationConstants.authenticationURI, (userPrincipal).getUserURI());
            }
            request.setAttribute(SerializationConstants.userPrincipal, userPrincipal);
            request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD));
            ret = true;

            // Check if the token is older than the refresh window. If so, create a new cookie with an updated timestamp.
            try {
                if (currentTime < token.getTimestamp()
                        || (currentTime - token.getTimestamp() >= tokenRefreshWindow)) { // if current time is less than the token's time, we'll issue a new cookie. That should only ever happen upon overflow of the number of milliseconds from the epoch.
                    String cookieval = createEncryptedToken(token.getUsername(), token.getRemoteAddress());
                    Cookie newTokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, cookieval);
                    newTokenCookie.setPath("/");
                    if (customTokenRefresh) {
                        request.setAttribute(ANZO_REFRESH_COOKIE_ATTRIBUTE, newTokenCookie);
                    } else {
                        response.addCookie(newTokenCookie);
                    }
                }
            } catch (AnzoException e) {
                log.error(LogUtils.SECURITY_MARKER,
                        "Could NOT update timestamp on authentication token. Authentication session may end prematurely.",
                        e);
            }
        }
    } else {
        // This is NOT a protected resource so just let it be served.
        ret = true;
    }

    log.debug(LogUtils.SECURITY_MARKER, "Returning from 'authenticate' with {} for path {}", ret, uri);
    return ret;
}

From source file:org.josso.jaspi.agent.JASPISSOAuthModule.java

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {

    HttpServletRequest hreq = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse hres = (HttpServletResponse) messageInfo.getResponseMessage();

    if (log.isDebugEnabled()) {
        log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
    }//from   w  w  w.  j  a v a2s .  c  o  m

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath)) {
            contextPath = "/";
        }

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            if (log.isDebugEnabled()) {
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());
            }
            AuthStatus status = AuthStatus.SUCCESS;
            return status;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");
            }

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to login url '" + loginUrl + "'");
            }

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");
            }

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled()) {
                log.debug("Redirecting to logout url '" + logoutUrl + "'");
            }

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            // Request is authorized for this URI
            return AuthStatus.SEND_CONTINUE;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking for SSO cookie");
        }
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap == null) {
            synchronized (this) {
                sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
                if (sessionMap == null) {
                    sessionMap = Collections.synchronizedMap(new HashMap());
                    hreq.getSession().getServletContext().setAttribute(KEY_SESSION_MAP, sessionMap);
                }
            }
        }

        LocalSession localSession = (LocalSession) sessionMap.get(session.getId());
        if (localSession == null) {
            localSession = new JASPILocalSession(session);
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not Supported : session.addSessionListener(this);
            sessionMap.put(session.getId(), localSession);

        }

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            JASPISSOAgentRequest customAuthRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);

            _agent.processRequest(customAuthRequest);

            // Request is authorized
            return AuthStatus.SEND_CONTINUE;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = this.getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                AuthStatus status = AuthStatus.SEND_CONTINUE;
                return status;
            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                // If saved request is NOT null, we're in the middle of another process ...
                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, attempting automatic login");
                    }

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled()) {
                        log.debug("Redirecting to login url '" + loginUrl + "'");
                    }

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    //hreq.getRequestDispatcher(loginUrl).forward(hreq, hres);
                    AuthStatus status = AuthStatus.SEND_CONTINUE;
                    return status;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("SSO cookie is not present, but login optional process is not required");
                    }
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("SSO cookie is not present, checking for outbound relaying");
            }

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                AuthStatus status = AuthStatus.SUCCESS;
                return status;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            // Ignored resources are authorized
            return AuthStatus.SUCCESS;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled()) {
            log.debug("Session is: " + session);
        }

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Executing agent...");
        }

        // ------------------------------------------------------------------
        // Check if a user has been authenticated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");
        }

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled()) {
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));
            }

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            JASPISSOAgentRequest relayRequest;

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");
            }

            relayRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                if (log.isDebugEnabled()) {
                    log.debug("Outbound relaying failed for assertion id [" + assertionId
                            + "], no Principal found.");
                }
                // Throw an exception, we will handle it below !
                throw new RuntimeException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            } else {
                // Add the SSOUser as a Principal
                if (!clientSubject.getPrincipals().contains(entry.principal)) {
                    clientSubject.getPrincipals().add(entry.principal);
                }
                SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId,
                        relayRequest.getNodeId());
                List<String> rolesList = new ArrayList<String>();

                for (int i = 0; i < ssoRolePrincipals.length; i++) {
                    if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                        continue;
                    }
                    rolesList.add(ssoRolePrincipals[i].getName());

                    clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                    log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
                }

                registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                        rolesList.toArray(new String[rolesList.size()]));
            }

            if (log.isDebugEnabled()) {
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");
            }

            if (log.isDebugEnabled()) {
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");
            }

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                }
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to original '" + requestURI + "'");
                }
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            AuthStatus status = AuthStatus.SEND_SUCCESS;
            return status;
        }

        if (log.isDebugEnabled()) {
            log.debug("Creating Security Context for Session [" + session + "]");
        }
        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled()) {
            log.debug("Executed agent.");
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled()) {
            log.debug("Process request for '" + hreq.getRequestURI() + "'");
        }

        if (entry != null) {
            if (log.isDebugEnabled()) {
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            }
            // Add the SSOUser as a Principal
            if (!clientSubject.getPrincipals().contains(entry.principal)) {
                clientSubject.getPrincipals().add(entry.principal);
            }
            SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, r.getNodeId());
            List<String> rolesList = new ArrayList<String>();
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) {
                    continue;
                }
                rolesList.add(ssoRolePrincipals[i].getName());
                clientSubject.getPrincipals().add(ssoRolePrincipals[i]);
                log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]);
            }
            registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId,
                    rolesList.toArray(new String[rolesList.size()]));
        } else {
            log.debug("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {
                if (log.isDebugEnabled()) {
                    log.debug("SSO Session is not valid, attempting automatic login");
                }

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled()) {
                    log.debug("Redirecting to login url '" + loginUrl + "'");
                }

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

                // Request is authorized for this URI
                return AuthStatus.SEND_CONTINUE;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        clearSavedRequestURLs(hreq, hres);

        AuthStatus status = AuthStatus.SUCCESS;
        return status;
    } catch (Throwable t) {
        log.warn(t.getMessage(), t);
        throw new AuthException(t.getMessage());
        //return AuthStatus.FAILURE;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]");
        }
    }
}

From source file:org.josso.wls10.agent.WLSAgentServletFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {//from  w ww  .  j av  a 2  s  .co m
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(request.getServerName(), contextPath)) {
            filterChain.doFilter(hreq, hres);
            log.warn("JOSSO WLS 10 Filter is running on a non-JOSSO Partner application!");

            return;
        }

        String nodeId = hreq.getParameter("josso_node");
        if (nodeId != null) {
            if (log.isDebugEnabled())
                log.debug("Storing JOSSO Node id : " + nodeId);
            _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId);
        } else {
            nodeId = _agent.getAttribute(hreq, "JOSSO_NODE");
            if (log.isDebugEnabled())
                log.debug("Found JOSSO Node id : " + nodeId);
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(request.getServerName(), contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // logout user (remove data from the session and webserver)
            // (The LoginModule.logout method is never called 
            // for the WebLogic Authentication providers or custom Authentication providers. 
            // This is simply because once the principals are created and placed into a subject, 
            // the WebLogic Security Framework no longer controls the lifecycle of the subject)
            _agent.prepareNonCacheResponse(hres);
            ServletAuthentication.logout(hreq);

            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);
        LocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, nodeId,
                    hreq, hres);
            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can go back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            SSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession,
                    assertionId, nodeId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {
                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r;
        log.debug("Creating Security Context for Session [" + session + "]");
        r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                jossoSessionId, localSession, null, nodeId, hreq, hres);

        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // TODO : Not supported ... session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can go back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:com.swdouglass.joid.server.OpenIdServlet.java

public void doQuery(String query, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    debug("\nrequest\n-------\n" + query + "\n");

    if (!(openId.canHandle(query))) {
        returnError(query, response);//from  w  w w.  ja  v a  2 s  .c  o m
        return;
    }
    try {
        boolean isAuth = openId.isAuthenticationRequest(query);
        HttpSession session = request.getSession(true);
        String username = getLoggedIn(request);
        debug("[OpenIdServlet] Logged in as: " + username);

        if (this.captchaPrivateKey != null) {
            session.setAttribute(INIT_CAPTCHA_PRIVATE_KEY, this.captchaPrivateKey);
        }
        if (request.getParameter(AuthenticationRequest.OPENID_TRUST_ROOT) != null) {
            session.setAttribute(AuthenticationRequest.OPENID_TRUST_ROOT,
                    request.getParameter(AuthenticationRequest.OPENID_TRUST_ROOT));
        }
        if (request.getParameter(AuthenticationRequest.OPENID_RETURN_TO) != null) {
            session.setAttribute(AuthenticationRequest.OPENID_RETURN_TO,
                    request.getParameter(AuthenticationRequest.OPENID_RETURN_TO));
        }
        // If we're handling an authentication request, and the user has not been authenticated,
        // redirect to the login page.
        if (isAuth && username == null) {
            // TODO: should ask user to accept realm even if logged in, but only once
            // ask user to accept this realm
            request.setAttribute(QUERY, query);
            String realm = request.getParameter(AuthenticationRequest.OPENID_REALM);
            if (realm == null) {
                realm = request.getParameter(AuthenticationRequest.OPENID_RETURN_TO);
            }
            request.setAttribute(AuthenticationRequest.OPENID_REALM, realm);
            session.setAttribute(QUERY, query);
            //if claimed_id is null then use identity instead (because of diffs between v2 & v1 of spec)
            if (request.getParameter(AuthenticationRequest.OPENID_CLAIMED_ID) == null) {
                session.setAttribute(AuthenticationRequest.OPENID_CLAIMED_ID,
                        request.getParameter(AuthenticationRequest.OPENID_IDENTITY));
            } else {
                session.setAttribute(AuthenticationRequest.OPENID_CLAIMED_ID,
                        request.getParameter(AuthenticationRequest.OPENID_CLAIMED_ID));
            }
            session.setAttribute(AuthenticationRequest.OPENID_REALM,
                    request.getParameter(AuthenticationRequest.OPENID_REALM));
            response.sendRedirect(loginPage);
            return;
        }
        String s = openId.handleRequest(query);
        debug("\nresponse\n--------\n" + s + "\n");
        if (isAuth) {
            AuthenticationRequest authReq = (AuthenticationRequest) MessageFactory.parseRequest(query);
            //String claimedId = (String) session.getAttribute(ID_CLAIMED);
            /*TODO: Ensure that the previously claimed id is the same as the just
            passed in claimed id. */
            String identity;
            if (request.getParameter(AuthenticationRequest.OPENID_CLAIMED_ID) == null) {
                identity = request.getParameter(AuthenticationRequest.OPENID_IDENTITY);
            } else {
                identity = authReq.getClaimedIdentity();
            }
            User user = (User) session.getAttribute(USER_ATTRIBUTE);
            debug("User.username: " + user);
            debug("identity: " + identity);
            if (getUserManager().canClaim(user, identity)) {
                //String returnTo = authReq.getReturnTo();
                String returnTo = (String) session.getAttribute(AuthenticationRequest.OPENID_RETURN_TO);
                String delim = (returnTo.indexOf('?') >= 0) ? "&" : "?";
                s = response.encodeRedirectURL(returnTo + delim + s);
                debug("sending redirect to: " + s);
                response.sendRedirect(s);
            } else {
                throw new OpenIdException("User cannot claim this id.");
            }

        } else {
            // Association request
            int len = s.length();
            PrintWriter out = response.getWriter();
            response.setHeader("Content-Length", Integer.toString(len));
            if (openId.isAnErrorResponse(s)) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            }
            out.print(s);
            out.flush();
        }
    } catch (OpenIdException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}