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.esgf.globusonline.GOauthView2Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.GET)
public ModelAndView doGet(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String auth_code = request.getParameter("code");
    String[] file_urls;/*  w w w.jav  a 2s.  co  m*/
    String[] file_names;
    String dataset_id = "";
    String BaseURL = "";
    //Get the session, so we can retrieve state.
    HttpSession session = request.getSession(false);
    if (session == null) {
    } else {
        //grab the dataset name, file names and urls from the query string
        file_names = (String[]) session.getAttribute("fileNames");
        //LOG.info("filenames are:" + file_names.length);
        file_urls = (String[]) session.getAttribute("fileUrls");
        dataset_id = (String) session.getAttribute("datasetName");
        //System.out.println("Auth2, session id is:" + session.getId());
        //System.out.println("Your dataset name is: " + dataset_id);
        BaseURL = (String) session.getAttribute("baseurl");
    }
    String esg_user = "";
    String esg_password = "";

    Map<String, Object> model = new HashMap<String, Object>();
    Properties GOProperties = getGOProperties();
    String PortalID = (String) GOProperties.getProperty("GOesgfPortalID", "bogususer");
    String PortalPass = (String) GOProperties.getProperty("GOesgfPortalPassword", "boguspassword");

    try {
        // Create the client object so we can use its methods
        GoauthClient cli = new GoauthClient("nexus.api.globusonline.org", "globusonline.org", PortalID,
                PortalPass);
        cli.setIgnoreCertErrors(true);

        //System.out.println("Your auth_code is: " + auth_code);
        JSONObject accessTokenJSON = cli.exchangeAuthCodeForAccessToken(auth_code);
        String accessToken = accessTokenJSON.getString("access_token");

        //System.out.println("Your access token is: " + accessToken);

        // We can validate the token by using this call:
        JSONObject tokenInfo = cli.validateAccessToken(accessToken);
        System.out.println("AccessToken from Globus Online is valid.");

        //Put the go Username into the session
        session.setAttribute("gousername", tokenInfo.getString("user_name"));
        session.setAttribute("goaccesstoken", accessTokenJSON);
    } catch (JSONException e) {
        //logger.error("Error getting access_token", e);
        //throw new ValueErrorException();
    } catch (org.globusonline.nexus.exception.NexusClientException e) {
        String error_msg = "GlobusOnline Configuration error. The administrator must create /esg/config/globusonline.properties and populate it with GOesgfPortalID and GOesgfPortalPassword";
        System.out.println(error_msg);
        //e.printStackTrace();
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);

    }

    return new ModelAndView("redirect:https://globusonline.org/xfer/SelectDestination"
            + "?method=post&ep=GC&title=Select Destination&message=Choose your destination for dataset "
            + dataset_id
            + "     Your Globus Connect endpoint has been selected by default. If you would prefer to transfer to a different endpoint, you can select it below.&button=Start Transfer&transferoptions=BECG&action="
            + URLEncoder.encode(response.encodeRedirectURL(BaseURL + "/esgf-web-fe/goauthview3"), "UTF-8"),
            model);
}

From source file:org.springframework.security.oauth.consumer.filter.OAuthConsumerContextFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
    context.setDetails(request);// w w w  .j  a  v  a 2s.com

    Map<String, OAuthConsumerToken> rememberedTokens = getRememberMeServices().loadRememberedTokens(request,
            response);
    Map<String, OAuthConsumerToken> accessTokens = new TreeMap<String, OAuthConsumerToken>();
    Map<String, OAuthConsumerToken> requestTokens = new TreeMap<String, OAuthConsumerToken>();
    if (rememberedTokens != null) {
        for (Map.Entry<String, OAuthConsumerToken> tokenEntry : rememberedTokens.entrySet()) {
            OAuthConsumerToken token = tokenEntry.getValue();
            if (token != null) {
                if (token.isAccessToken()) {
                    accessTokens.put(tokenEntry.getKey(), token);
                } else {
                    requestTokens.put(tokenEntry.getKey(), token);
                }
            }
        }
    }

    context.setAccessTokens(accessTokens);
    OAuthSecurityContextHolder.setContext(context);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute() + "'.");
    }

    try {
        try {
            request.setAttribute(getAccessTokensRequestAttribute(),
                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
            chain.doFilter(request, response);
        } catch (Exception e) {
            try {
                ProtectedResourceDetails resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(
                        e);
                String neededResourceId = resourceThatNeedsAuthorization.getId();
                while (!accessTokens.containsKey(neededResourceId)) {
                    OAuthConsumerToken token = requestTokens.remove(neededResourceId);
                    if (token == null) {
                        token = getTokenServices().getToken(neededResourceId);
                    }

                    String verifier = request.getParameter(OAuthProviderParameter.oauth_verifier.toString());
                    // if the token is null OR
                    // if there is NO access token and (we're not using 1.0a or the verifier is not null)
                    if (token == null || (!token.isAccessToken()
                            && (!resourceThatNeedsAuthorization.isUse10a() || verifier == null))) {
                        //no token associated with the resource, start the oauth flow.
                        //if there's a request token, but no verifier, we'll assume that a previous oauth request failed and we need to get a new request token.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining request token for resource: " + neededResourceId);
                        }

                        //obtain authorization.
                        String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
                        token = getConsumerSupport().getUnauthorizedRequestToken(neededResourceId, callbackURL);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Request token obtained for resource " + neededResourceId + ": " + token);
                        }

                        //okay, we've got a request token, now we need to authorize it.
                        requestTokens.put(neededResourceId, token);
                        getTokenServices().storeToken(neededResourceId, token);
                        String redirect = getUserAuthorizationRedirectURL(resourceThatNeedsAuthorization, token,
                                callbackURL);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Redirecting request to " + redirect
                                    + " for user authorization of the request token for resource "
                                    + neededResourceId + ".");
                        }

                        request.setAttribute(
                                "org.springframework.security.oauth.consumer.AccessTokenRequiredException", e);
                        this.redirectStrategy.sendRedirect(request, response, redirect);
                        return;
                    } else if (!token.isAccessToken()) {
                        //we have a presumably authorized request token, let's try to get an access token with it.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining access token for resource: " + neededResourceId);
                        }

                        //authorize the request token and store it.
                        try {
                            token = getConsumerSupport().getAccessToken(token, verifier);
                        } finally {
                            getTokenServices().removeToken(neededResourceId);
                        }

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Access token " + token + " obtained for resource " + neededResourceId
                                    + ". Now storing and using.");
                        }

                        getTokenServices().storeToken(neededResourceId, token);
                    }

                    accessTokens.put(neededResourceId, token);

                    try {
                        //try again
                        if (!response.isCommitted()) {
                            request.setAttribute(getAccessTokensRequestAttribute(),
                                    new ArrayList<OAuthConsumerToken>(accessTokens.values()));
                            chain.doFilter(request, response);
                        } else {
                            //dang. what do we do now?
                            throw new IllegalStateException(
                                    "Unable to reprocess filter chain with needed OAuth2 resources because the response is already committed.");
                        }
                    } catch (Exception e1) {
                        resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e1);
                        neededResourceId = resourceThatNeedsAuthorization.getId();
                    }
                }
            } catch (OAuthRequestFailedException eo) {
                fail(request, response, eo);
            } catch (Exception ex) {
                Throwable[] causeChain = getThrowableAnalyzer().determineCauseChain(ex);
                OAuthRequestFailedException rfe = (OAuthRequestFailedException) getThrowableAnalyzer()
                        .getFirstThrowableOfType(OAuthRequestFailedException.class, causeChain);
                if (rfe != null) {
                    fail(request, response, rfe);
                } else {
                    // Rethrow ServletExceptions and RuntimeExceptions as-is
                    if (ex instanceof ServletException) {
                        throw (ServletException) ex;
                    } else if (ex instanceof RuntimeException) {
                        throw (RuntimeException) ex;
                    }

                    // Wrap other Exceptions. These are not expected to happen
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        OAuthSecurityContextHolder.setContext(null);
        HashMap<String, OAuthConsumerToken> tokensToRemember = new HashMap<String, OAuthConsumerToken>();
        tokensToRemember.putAll(requestTokens);
        tokensToRemember.putAll(accessTokens);
        getRememberMeServices().rememberTokens(tokensToRemember, request, response);
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void uploadDocumentStructure(HttpServletRequest req, HttpServletResponse resp, String repositoryName,
        InputStream contentInputStream) {
    // This will trigger validation
    String id;//from  ww  w  .  j av a 2s .  c o  m
    String name;
    String description;
    String keywords;
    try {
        id = getField(req, resp, "id");
        keywords = checkParameter(params, req, resp, repositoryName, "keywords");
        name = checkParameter(params, req, resp, repositoryName, "name");
        repositoryName = getField(req, resp, "repository");
        description = checkParameter(params, req, resp, repositoryName, "description");
    } catch (FieldNotFoundException e) {
        return;
    }

    Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
    RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();

    try {
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);
        StringBuilder url = new StringBuilder(getRepositoryURL(req, repositoryName));
        Author author = null;
        try {
            author = repositoryService.findAuthorByName(ticket, ticket.getUser().getName());
        } catch (AuthorNotFoundException anfe) {
            author = Author.UNKNOWN;
        }
        Document document = new Document();
        document.setName(name);
        document.setDescription(description);
        document.setParent(id);
        document.setPosition(new Integer(1));
        document.setImportance(Node.IMPORTANCE_MEDIUM);
        document.setDate(new Date());
        document.setRelations(new HashSet());
        document.addCategory(Category.UNKNOWN);
        DocumentMetaData metaData = new DocumentMetaData();
        metaData.setDate(new Date());
        metaData.setTitle(name);
        metaData.setKeywords(keywords);
        metaData.setUrl(url.toString());
        metaData.setAuthor(author);
        document.setMetaData(metaData);

        String path = (String) params.get("filename");
        document.setPath(path);
        document.setTypecode(Types.getTypeForFile(path));
        DocumentProperties properties = document.dumpProperties();
        document = repositoryService.createDocument(ticket, properties);
        statsService.incCreatedDocuments();
        if (contentInputStream != null) {
            document = (Document) repositoryService.updateContent(ticket, document.getId(), contentInputStream);
            url.append(document.getPath());
            resp.sendRedirect(resp.encodeRedirectURL(url.toString()));
            return;
        } else {
            logErrorAndForward(req, resp, repositoryName, null,
                    "There was a problem trying to upload the document.");
        }
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to create the object.");
    } finally {
        if (contentInputStream != null) {
            try {
                contentInputStream.close();
            } catch (IOException e) {
                logErrorAndForward(req, resp, repositoryName, e,
                        "There was a problem trying to create the object.");
            }
        }
    }
}

From source file:com.wso2telco.gsma.authenticators.ussd.USSDPinAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    log.info("Initiating authentication request");

    UserStatus userStatus = (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM);

    if (context.getProperty(Constants.IS_PIN_RESET) == null) {
        context.setProperty(Constants.IS_PIN_RESET, false);
    }//from ww w. j a va  2  s .  co m
    String retryParam = "";
    boolean isRegistering = (boolean) context.getProperty(Constants.IS_REGISTERING);
    boolean isPinReset = (boolean) context.getProperty(Constants.IS_PIN_RESET);
    boolean isProfileUpgrade = (boolean) context.getProperty(Constants.IS_PROFILE_UPGRADE);
    boolean securityQuestionsShown = context.getProperty(Constants.IS_SECURITY_QUESTIONS_SHOWN) != null
            && (boolean) context.getProperty(Constants.IS_SECURITY_QUESTIONS_SHOWN);

    String msisdn = (String) context.getProperty(Constants.MSISDN);

    // USSDPinAuthenticator cannot proceed without an msisdn
    if (StringUtils.isEmpty(msisdn)) {
        terminateAuthentication(context);
    }

    String serviceProviderName = context.getSequenceConfig().getApplicationConfig().getApplicationName();

    if (log.isDebugEnabled()) {
        log.debug("Registering : " + isRegistering);
        log.debug("Pin reset : " + isPinReset);
        log.debug("MSISDN : " + msisdn);
        log.debug("Service provider : " + serviceProviderName);
    }

    try {

        String loginPage = getAuthEndpointUrl(context);

        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
                context.getCallerSessionKey(), context.getContextIdentifier());

        if (serviceProviderName.equals("wso2_sp_dashboard")) {
            serviceProviderName = configurationService.getDataHolder().getMobileConnectConfig().getUssdConfig()
                    .getDashBoard();
        }
        String operator = (String) context.getProperty("operator");

        savePinConfigToContext(context, isRegistering, msisdn, isPinReset, isProfileUpgrade);

        // send ussd message only when, request is not pin reset and any of followings,
        // securityQuestionsShown : when user has entered security questions when profile upgrade flow
        // or when user comes via LOA 3 login
        if (securityQuestionsShown || (!isRegistering && !isProfileUpgrade && !isPinReset)) {
            DBUtils.insertAuthFlowStatus(msisdn, Constants.STATUS_PENDING, context.getContextIdentifier());
            USSDPinFutureCallback futureCallback = userStatus != null
                    ? new USSDPinFutureCallback(userStatus.cloneUserStatus())
                    : new USSDPinFutureCallback();
            sendUssd(context, isRegistering, msisdn, serviceProviderName, operator, futureCallback);
        }

        String redirectUrl = response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&redirect_uri="
                + context.getProperty("redirectURI") + "&authenticators=" + getName() + ":" + "LOCAL"
                + retryParam + "&sessionDataKey=" + context.getContextIdentifier();

        DataPublisherUtil.updateAndPublishUserStatus(userStatus, DataPublisherUtil.UserState.USSDPIN_REDIRECT,
                "Redirect URL : " + redirectUrl);

        response.sendRedirect(redirectUrl);

    } catch (IOException e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.USSDPIN_AUTH_PROCESSING_FAIL, e.getMessage());
        log.error("Error occurred while redirecting the request", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (SQLException | AuthenticatorException e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.USSDPIN_AUTH_PROCESSING_FAIL, e.getMessage());
        log.error("Error occurred while inserting registration status", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    } catch (RemoteUserStoreManagerServiceUserStoreExceptionException e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.USSDPIN_AUTH_PROCESSING_FAIL, e.getMessage());
        log.error("Error occurred while getting user pin", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

protected void sendRedirect(HttpServletRequest request, javax.servlet.http.HttpServletResponse response,
        String virtualLink) throws IOException {
    // send redirect always via j2ee method
    // B00004862//from ww w  . j a  va 2 s.  c o  m

    try {
        // #00005082: try to use absolute URLs for redirects if possible
        String url = WGA.get(request, response, _core).urlBuilder(virtualLink).build(true);
        response.sendRedirect(response.encodeRedirectURL(url));
    } catch (WGException e) {
        _core.getLog().warn("Unable to create absolute Redirect URL. Using relative URL", e);
        response.sendRedirect(response.encodeRedirectURL(virtualLink));
    }

}

From source file:fll.web.admin.UploadSubjectiveData.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();

    final File file = File.createTempFile("fll", null);
    Connection connection = null;
    try {/*from  ww  w.  j  a v  a 2s  . c o  m*/
        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        final FileItem subjectiveFileItem = (FileItem) request.getAttribute("subjectiveFile");
        subjectiveFileItem.write(file);

        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();
        saveSubjectiveData(file, Queries.getCurrentTournament(connection),
                ApplicationAttributes.getChallengeDescription(application), connection, application);
        message.append("<p id='success'><i>Subjective data uploaded successfully</i></p>");
    } catch (final SAXParseException spe) {
        final String errorMessage = String.format(
                "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.",
                spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage());
        message.append("<p class='error'>" + errorMessage + "</p>");
        LOGGER.error(errorMessage, spe);
    } catch (final SAXException se) {
        final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else";
        message.append("<p class='error'>" + errorMessage + "</p>");
        LOGGER.error(errorMessage, se);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error saving subjective data into the database: " + sqle.getMessage()
                + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error saving subjective data into the database", sqle);
    } catch (final ParseException e) {
        message.append(
                "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    } catch (final FileUploadException e) {
        message.append("<p class='error'>Error processing subjective data upload: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error processing subjective data upload", e);
    } catch (final Exception e) {
        message.append(
                "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    } finally {
        if (!file.delete()) {
            LOGGER.warn("Unable to delete file " + file.getAbsolutePath() + ", setting to delete on exit");
            file.deleteOnExit();
        }
        SQLFunctions.close(connection);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));
}

From source file:org.josso.wls92.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() + " [" + hreq.getRequestURL() + "]");

    try {/*w  w w  . j  av a2  s  . c  o  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 9.2 Filter is running on a non-JOSSO Partner application!");
            return;
        }

        // ------------------------------------------------------------------
        // 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, 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 and a security check without assertion was received ...
            // This means that the user could not be identified during a login optional process ...
            // 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 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 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, 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, 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() + " [" + hreq.getRequestURL() + "]");
    }
}

From source file:org.josso.wls81.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() + " [" + hreq.getRequestURL() + "]");

    try {//from ww  w .  ja va  2 s .  c  o  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 8.1 Filter is running on a non-JOSSO Partner application!");
            return;
        }

        // ------------------------------------------------------------------
        // 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, 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 and a security check without assertion was received ...
            // This means that the user could not be identified during a login optional process ...
            // 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 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 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, 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 the user to the original request URI (which will cause
            // the original request to be restored)

            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, 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() + " [" + hreq.getRequestURL() + "]");
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void register(HttpServletRequest req, HttpServletResponse resp) {

    String repositoryName;/*w ww .  jav  a  2  s .c o m*/
    String firstName;
    String secondName;
    String email;
    String username;
    String password;

    try {
        repositoryName = getField(req, resp, "repository");
        username = getField(req, resp, "username");
        firstName = getField(req, resp, "name");
        secondName = getField(req, resp, "surname");
        email = getField(req, resp, "email");
        password = getField(req, resp, "password");
    } catch (FieldNotFoundException e) {
        return;
    }

    // handle captcha
    boolean captchaOk = false;
    String captchaId = req.getSession().getId();
    String response = req.getParameter("j_captcha_response");
    try {
        captchaOk = CaptchaService.getInstance().validateResponseForID(captchaId, response);
    } catch (CaptchaServiceException e) {
        //should not happen, may be thrown if the id is not valid 
    }
    if (!captchaOk) {
        if (logger.isDebugEnabled()) {
            logErrorAndForward(req, resp, repositoryName,
                    new InvalidOperationException("Invalid captcha value"), "Invalid captcha value");
            return;
        }
    }

    RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();
    SecurityService securityService = JLibraryServiceFactory.getInstance(profile).getSecurityService();

    Credentials credentials = new Credentials();
    credentials.setUser(User.ADMIN_NAME);
    credentials.setPassword(User.DEFAULT_PASSWORD);
    Ticket adminTicket = null;

    try {
        adminTicket = securityService.login(credentials, repositoryName);
        Repository repository = repositoryService.findRepository(repositoryName, adminTicket);
        repository.setServerProfile(profile);

        UserProperties userProperties = new UserProperties();
        userProperties.addProperty(UserProperties.USER_ID, username);
        userProperties.addProperty(UserProperties.USER_NAME, username);
        userProperties.addProperty(UserProperties.USER_EMAIL, email);
        userProperties.addProperty(UserProperties.USER_FIRSTNAME, firstName);
        userProperties.addProperty(UserProperties.USER_LASTNAME, secondName);
        userProperties.addProperty(UserProperties.USER_PASSWORD, password);
        userProperties.addProperty(UserProperties.USER_ADMIN, Boolean.FALSE);
        userProperties.addProperty(UserProperties.USER_REPOSITORY, repository.getId());
        securityService.createUser(adminTicket, userProperties);
        statsService.incRegisteredUsers();
        String url = getRepositoryURL(req, repositoryName);
        resp.sendRedirect(resp.encodeRedirectURL(url));

        resp.getOutputStream().flush();
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to register the user.");
    } finally {
        if (adminTicket != null) {
            try {
                securityService.disconnect(adminTicket);
            } catch (SecurityException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:org.josso.servlet.agent.GenericServletSSOAgentFilter.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 {//  w w w.  j av  a  2s . c  o  m
        // ------------------------------------------------------------------
        // 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)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        // ------------------------------------------------------------------
        // 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());
        }

        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);

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

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            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;
            }
        }

        // Get our session ...

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        GenericServletLocalSession 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() + "'");
            }

            GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(
                    cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession,
                    null, 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 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));
                    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;
        }

        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 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);

            GenericServletSSOAgentRequest relayRequest;

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

            relayRequest = (GenericServletSSOAgentRequest) 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!
                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("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 the user to the original request URI (which will cause
            // the original request to be restored)
            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 = 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.");

        // 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.
            // 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 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));
                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());
    }
}