Example usage for javax.servlet.http HttpServletRequest isSecure

List of usage examples for javax.servlet.http HttpServletRequest isSecure

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isSecure.

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:ru.org.linux.topic.TopicListController.java

@RequestMapping("/section-rss.jsp")
public ModelAndView showRSS(HttpServletRequest request, TopicListRequest topicListForm,
        @RequestParam(value = "group", defaultValue = "0") int groupId) throws Exception {

    final String[] filterValues = { "all", "notalks", "tech" };
    final Set<String> filterValuesSet = new HashSet<String>(Arrays.asList(filterValues));

    if (topicListForm.getFilter() != null && !filterValuesSet.contains(topicListForm.getFilter())) {
        throw new UserErrorException("?  filter");
    }//from   w  ww.  j  a  v a  2 s .  c  o  m
    boolean notalks = topicListForm.getFilter() != null && "notalks".equals(topicListForm.getFilter());
    boolean tech = topicListForm.getFilter() != null && "tech".equals(topicListForm.getFilter());

    if (topicListForm.getSection() == null) {
        topicListForm.setSection(1);
    }

    String userAgent = request.getHeader("User-Agent");
    final boolean feedBurner = userAgent != null && userAgent.contains("FeedBurner");

    if (topicListForm.getSection() == 1 && groupId == 0 && !notalks && !tech && !feedBurner
            && request.getParameter("noredirect") == null) {
        return new ModelAndView(new RedirectView("http://feeds.feedburner.com/org/LOR"));
    }

    Section section = sectionService.getSection(topicListForm.getSection());
    String ptitle = section.getName();

    Group group = null;
    if (groupId != 0) {
        group = groupDao.getGroup(groupId);
        ptitle += " - " + group.getTitle();
    }

    checkRequestConditions(section, group, topicListForm);

    ModelAndView modelAndView = new ModelAndView("section-rss");

    modelAndView.addObject("group", group);
    modelAndView.addObject("section", section);
    modelAndView.addObject("ptitle", ptitle);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH, -3);

    List<Topic> messages = topicListService.getRssTopicsFeed(section, group, calendar.getTime(), notalks, tech,
            feedBurner);

    modelAndView.addObject("messages", prepareService.prepareMessages(messages, request.isSecure()));
    return modelAndView;
}

From source file:ru.org.linux.group.GroupController.java

private ModelAndView forum(@PathVariable("group") String groupName,
        @RequestParam(defaultValue = "0", value = "offset") int offset,
        @RequestParam(defaultValue = "false") boolean lastmod, HttpServletRequest request,
        HttpServletResponse response, Integer year, Integer month) throws Exception {
    Map<String, Object> params = new HashMap<>();
    Template tmpl = Template.getTemplate(request);

    boolean showDeleted = request.getParameter("deleted") != null;
    params.put("showDeleted", showDeleted);

    Section section = sectionService.getSection(Section.SECTION_FORUM);
    params.put("groupList", groupDao.getGroups(section));

    Group group = groupDao.getGroup(section, groupName);

    if (showDeleted && !"POST".equals(request.getMethod())) {
        return new ModelAndView(new RedirectView(group.getUrl()));
    }/*from  www  . jav a 2 s . c  om*/

    if (showDeleted && !tmpl.isSessionAuthorized()) {
        throw new AccessViolationException("  ");
    }

    boolean firstPage;

    if (offset != 0) {
        firstPage = false;

        if (offset < 0) {
            throw new ServletParameterBadValueException("offset",
                    "offset    ");
        }

        if (year == null && offset > MAX_OFFSET) {
            return new ModelAndView(new RedirectView(group.getUrl() + "archive"));
        }
    } else {
        firstPage = true;
    }

    params.put("firstPage", firstPage);
    params.put("offset", offset);
    params.put("prevPage", offset - tmpl.getProf().getTopics());
    params.put("nextPage", offset + tmpl.getProf().getTopics());
    params.put("lastmod", lastmod);

    boolean showIgnored = false;
    if (request.getParameter("showignored") != null) {
        showIgnored = "t".equals(request.getParameter("showignored"));
    }

    params.put("showIgnored", showIgnored);

    params.put("group", group);

    if (group.getImage() != null) {
        try {
            params.put("groupImagePath", '/' + tmpl.getStyle() + group.getImage());
            ImageInfo info = new ImageInfo(
                    configuration.getHTMLPathPrefix() + tmpl.getStyle() + group.getImage());
            params.put("groupImageInfo", info);
        } catch (BadImageException ex) {
            params.put("groupImagePath", null);
            params.put("groupImageInfo", null);
        }
    } else {
        params.put("groupImagePath", null);
        params.put("groupImageInfo", null);
    }

    params.put("section", section);

    params.put("groupInfo", prepareService.prepareGroupInfo(group, request.isSecure()));

    if (year != null) {
        if (year < 1990 || year > 3000) {
            throw new ServletParameterBadValueException("year", "  ");
        }

        if (month < 1 || month > 12) {
            throw new ServletParameterBadValueException("month",
                    "  ??");
        }

        params.put("year", year);
        params.put("month", month);
        params.put("url", group.getUrl() + year + '/' + month + '/');
    } else {
        params.put("url", group.getUrl());
    }

    List<TopicsListItem> mainTopics = getTopics(group, tmpl.getProf().getMessages(), lastmod, year, month,
            tmpl.getProf().getTopics(), offset, showDeleted, showIgnored, tmpl.getCurrentUser());

    if (year == null && offset == 0 && !lastmod) {
        List<TopicsListItem> stickyTopics = getStickyTopics(group, tmpl.getProf().getMessages());

        params.put("topicsList", Lists.newArrayList(Iterables.concat(stickyTopics, mainTopics)));
    } else {
        params.put("topicsList", mainTopics);
    }

    if (year != null) {
        params.put("hasNext",
                offset + tmpl.getProf().getTopics() < getArchiveCount(group.getId(), year, month));
    } else {
        params.put("hasNext", offset < MAX_OFFSET && mainTopics.size() == tmpl.getProf().getTopics());
    }

    params.put("addable", groupPermissionService.isTopicPostingAllowed(group, tmpl.getCurrentUser()));

    response.setDateHeader("Expires", System.currentTimeMillis() + 90 * 1000);

    return new ModelAndView("group", params);
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//w  ww  .  j av a  2s . com
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./*from  w w w . j  av a2 s. c  o  m*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:ru.org.linux.topic.AddTopicController.java

@RequestMapping(value = "/add.jsp", method = RequestMethod.POST)
@CSRFNoAuto// w  ww.  j  ava 2 s  . c o m
public ModelAndView doAdd(HttpServletRequest request, @Valid @ModelAttribute("form") AddTopicRequest form,
        BindingResult errors, @ModelAttribute("ipBlockInfo") IPBlockInfo ipBlockInfo) throws Exception {
    Map<String, Object> params = new HashMap<String, Object>();

    Template tmpl = Template.getTemplate(request);
    HttpSession session = request.getSession();

    String image = processUploadImage(request);

    Group group = form.getGroup();

    prepareModel(form, params, tmpl.getCurrentUser());

    Section section = null;

    if (group != null) {
        section = sectionService.getSection(group.getSectionId());
    }

    User user;

    if (!tmpl.isSessionAuthorized()) {
        if (form.getNick() != null) {
            user = form.getNick();
        } else {
            user = userDao.getAnonymous();
        }

        if (form.getPassword() == null) {
            errors.rejectValue("password", null, "?? ?");
        }
    } else {
        user = tmpl.getCurrentUser();
    }

    user.checkBlocked(errors);

    IPBlockDao.checkBlockIP(ipBlockInfo, errors, user);

    if (group != null && !groupPermissionService.isTopicPostingAllowed(group, user)) {
        errors.reject(null,
                "??  ? ?   ? ");
    }

    String message = processMessage(form.getMsg(), form.getMode());

    if (user.isAnonymous()) {
        if (message.length() > MAX_MESSAGE_LENGTH_ANONYMOUS) {
            errors.rejectValue("msg", null, "  ?");
        }
    } else {
        if (message.length() > MAX_MESSAGE_LENGTH) {
            errors.rejectValue("msg", null, "  ?");
        }
    }

    Screenshot scrn = null;

    if (section != null && groupPermissionService.isImagePostingAllowed(section, tmpl.getCurrentUser())) {
        scrn = processUpload(session, image, errors);

        if (section.isImagepost() && scrn == null && !errors.hasErrors()) {
            errors.reject(null, " ??");
        }
    }

    Poll poll = null;

    if (section != null && section.isPollPostAllowed()) {
        poll = preparePollPreview(form);
    }

    Topic previewMsg = null;

    if (group != null) {
        previewMsg = new Topic(form, user, request.getRemoteAddr());

        Image imageObject = null;

        if (scrn != null) {
            imageObject = new Image(0, 0, "gallery/preview/" + scrn.getMainFile().getName(),
                    "gallery/preview/" + scrn.getIconFile().getName());
        }

        params.put("message", prepareService.prepareTopicPreview(previewMsg,
                tagService.parseSanitizeTags(form.getTags()), poll, request.isSecure(), message, imageObject));
    }

    if (!form.isPreviewMode() && !errors.hasErrors()) {
        CSRFProtectionService.checkCSRF(request, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors() && !tmpl.isSessionAuthorized()
            || ipBlockInfo.isCaptchaRequired()) {
        captcha.checkCaptcha(request, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors()) {
        dupeProtector.checkDuplication(request.getRemoteAddr(), false, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors() && group != null && section != null) {
        session.removeAttribute("image");

        Set<User> userRefs = lorCodeService.getReplierFromMessage(message);

        int msgid = messageDao.addMessage(request, form, message, group, user, scrn, previewMsg, userRefs);

        searchQueueSender.updateMessageOnly(msgid);

        Random random = new Random();

        String messageUrl = "view-message.jsp?msgid=" + msgid;

        if (!section.isPremoderated()) {
            return new ModelAndView(new RedirectView(messageUrl + "&nocache=" + random.nextInt()));
        }

        params.put("moderated", section.isPremoderated());
        params.put("url", messageUrl);

        return new ModelAndView("add-done-moderated", params);
    } else {
        return new ModelAndView("add", params);
    }
}

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data.//from  w w  w  .ja  v  a 2 s .com
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:com.cws.esolutions.security.filters.SSLEnforcementFilter.java

public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse,
        final FilterChain filterChain) throws ServletException, IOException {
    final String methodName = SSLEnforcementFilter.CNAME
            + "#doFilter(final ServletRequest req, final servletResponse res, final FilterChain filterChain) throws ServletException, IOException";

    if (DEBUG) {//from   w  w  w . j  a va 2 s  .c om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletRequest: {}", sRequest);
        DEBUGGER.debug("ServletResponse: {}", sResponse);
        DEBUGGER.debug("FilterChain: {}", filterChain);
    }

    final HttpServletRequest hRequest = (HttpServletRequest) sRequest;
    final HttpServletResponse hResponse = (HttpServletResponse) sResponse;

    if (DEBUG) {
        final HttpSession hSession = hRequest.getSession();

        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpServletResponse: {}", hResponse);
        DEBUGGER.debug("HttpSession: {}", hSession);

        DEBUGGER.debug("Dumping session content:");
        Enumeration<?> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String element = (String) sessionEnumeration.nextElement();
            Object value = hSession.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request content:");
        Enumeration<?> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String element = (String) requestEnumeration.nextElement();
            Object value = hRequest.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request parameters:");
        Enumeration<?> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String element = (String) paramsEnumeration.nextElement();
            Object value = hRequest.getParameter(element);

            DEBUGGER.debug("Parameter: {}; Value: {}", element, value);
        }
    }

    if (SSLEnforcementFilter.LOCALHOST.contains(sRequest.getServerName())) {
        if (DEBUG) {
            DEBUGGER.debug("Local request. Breaking out...");
        }

        filterChain.doFilter(sRequest, sResponse);

        return;
    }

    if ((this.ignoreHosts != null) && (this.ignoreHosts.length != 0)) {
        if (Arrays.asList(this.ignoreHosts).contains("ALL")) {
            if (DEBUG) {
                DEBUGGER.debug("ALL URIs are ignored. Breaking ...");
            }

            filterChain.doFilter(sRequest, sResponse);

            return;
        }

        for (String host : this.ignoreHosts) {
            String requestHost = host.trim();

            if (DEBUG) {
                DEBUGGER.debug(host);
                DEBUGGER.debug(requestHost);
            }

            if (StringUtils.equals(requestHost, sRequest.getServerName().trim())) {
                if (DEBUG) {
                    DEBUGGER.debug("Host found in ignore list. Not processing request!");
                }

                filterChain.doFilter(sRequest, sResponse);

                return;
            }
        }
    }

    if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) {
        if (Arrays.asList(this.ignoreURIs).contains("ALL")) {
            if (DEBUG) {
                DEBUGGER.debug("ALL URIs are ignored. Breaking ...");
            }

            filterChain.doFilter(sRequest, sResponse);

            return;
        }

        // no hosts in ignore list
        for (String uri : this.ignoreURIs) {
            String requestURI = uri.trim();

            if (DEBUG) {
                DEBUGGER.debug(uri);
                DEBUGGER.debug(requestURI);
            }

            if (StringUtils.equals(requestURI, hRequest.getRequestURI().trim())) {
                if (DEBUG) {
                    DEBUGGER.debug("URI found in ignore list. Not processing request!");
                }

                filterChain.doFilter(sRequest, sResponse);

                return;
            }
        }
    }

    if (hRequest.isSecure()) {
        // Request came in on a secure channel or
        // the HTTP:DECRYPTED header is true
        // do nothing
        if (DEBUG) {
            DEBUGGER.debug("Filter not applied to request - already secured. No action taken.");
        }

        filterChain.doFilter(sRequest, sResponse);

        return;
    }

    // secure it
    StringBuilder redirectURL = new StringBuilder().append(SSLEnforcementFilter.SECURE_URL_PREFIX)
            .append(sRequest.getServerName())
            .append((sRequest.getServerPort() != SSLEnforcementFilter.SECURE_URL_PORT)
                    ? ":" + sRequest.getServerPort()
                    : null)
            .append(hRequest.getRequestURI());

    if (StringUtils.isNotBlank(hRequest.getQueryString())) {
        redirectURL.append("?" + hRequest.getQueryString());
    }

    if (DEBUG) {
        DEBUGGER.debug("redirectURL: {}", redirectURL);
    }

    hResponse.sendRedirect(URLEncoder.encode(redirectURL.toString(), systemConfig.getEncoding()));

    return;
}

From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java

public HashMap<String, Object> processRenewal(CertEnrollmentRequest data, HttpServletRequest request,
        AuthCredentials credentials) throws EBaseException {
    try {/*from  w w w  .j a  v  a 2s  .com*/
        if (CMS.debugOn()) {
            HashMap<String, String> params = data.toParams();
            printParameterValues(params);
        }

        CMS.debug("RenewalProcessor: processRenewal()");

        startTiming("enrollment");
        request.setAttribute("reqType", "renewal");

        // in case of renew, "profile" is the orig profile
        // while "renewProfile" is the current profile used for renewal
        String renewProfileId = (this.profileID == null) ? data.getProfileId() : this.profileID;
        CMS.debug("RenewalProcessor: profile: " + renewProfileId);

        IProfile renewProfile = ps.getProfile(renewProfileId);
        if (renewProfile == null) {
            CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
            throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(renewProfileId)));
        }
        if (!ps.isProfileEnable(renewProfileId)) {
            CMS.debug("RenewalProcessor: Profile " + renewProfileId + " not enabled");
            throw new BadRequestDataException("Profile " + renewProfileId + " not enabled");
        }

        BigInteger certSerial = null;

        // get serial number from <SerialNumber> element (no auth required)
        CertId serial = data.getSerialNum();
        if (serial != null) {
            CMS.debug("RenewalProcessor: serial number: " + serial);
            certSerial = serial.toBigInteger();
        }

        // if not found, get serial number from profile input (no auth required)
        if (certSerial == null) {

            IPluginRegistry registry = (IPluginRegistry) CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);

            // find SerialNumRenewInput
            for (ProfileInput input : data.getInputs()) {

                String inputId = input.getId();
                if (inputId == null) {
                    throw new BadRequestException("Missing input ID");
                }

                String classId = input.getClassId();
                if (classId == null) {
                    throw new BadRequestException("Missing class ID in input " + inputId);
                }

                IPluginInfo pluginInfo = registry.getPluginInfo("profileInput", classId);
                if (pluginInfo == null) {
                    throw new BadRequestException("Unregistered class ID " + classId + " in input " + inputId);
                }

                String className = pluginInfo.getClassName();
                if (!SerialNumRenewInput.class.getName().equals(className)) {
                    // check the next input
                    continue;
                }

                CMS.debug("RenewalProcessor: found SerialNumRenewInput");
                ProfileAttribute attribute = input.getAttribute(SerialNumRenewInput.SERIAL_NUM);

                if (attribute == null) {
                    throw new BadRequestException(
                            "Missing attribute " + SerialNumRenewInput.SERIAL_NUM + " in input " + inputId);
                }

                String value = attribute.getValue();
                CMS.debug("RenewalProcessor: profile input " + SerialNumRenewInput.SERIAL_NUM + " value: "
                        + value);

                if (!StringUtils.isEmpty(value)) {
                    serial = new CertId(value);
                    certSerial = serial.toBigInteger();
                    break;
                }
            }
        }

        // if still not found, get serial number from client certificate (if provided)
        if (certSerial == null) {

            if (!request.isSecure()) {
                throw new BadRequestException("Missing serial number");
            }

            // ssl client auth is to be used
            // this is not authentication. Just use the cert to search
            // for orig request and find the right profile
            CMS.debug("RenewalProcessor: get serial number from client certificate");
            certSerial = getSerialNumberFromCert(request);
        }

        CMS.debug("processRenewal: serial number of cert to renew:" + certSerial.toString());
        ICertRecord rec = certdb.readCertificateRecord(certSerial);
        if (rec == null) {
            CMS.debug("processRenewal: cert record not found for serial number " + certSerial.toString());
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        // check to see if the cert is revoked or revoked_expired
        if ((rec.getStatus().equals(ICertRecord.STATUS_REVOKED))
                || (rec.getStatus().equals(ICertRecord.STATUS_REVOKED_EXPIRED))) {
            CMS.debug("processRenewal: cert found to be revoked. Serial number = " + certSerial.toString());
            throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_CA_CANNOT_RENEW_REVOKED_CERT"));
        }

        X509CertImpl origCert = rec.getCertificate();
        if (origCert == null) {
            CMS.debug("processRenewal: original cert not found in cert record for serial number "
                    + certSerial.toString());
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        Date origNotAfter = origCert.getNotAfter();
        CMS.debug("processRenewal: origNotAfter =" + origNotAfter.toString());

        String origSubjectDN = origCert.getSubjectDN().getName();
        CMS.debug("processRenewal: orig subj dn =" + origSubjectDN);

        IRequest origReq = getOriginalRequest(certSerial, rec);
        if (origReq == null) {
            CMS.debug("processRenewal: original request not found");
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_INTERNAL_ERROR"));
        }

        String profileId = origReq.getExtDataInString(IRequest.PROFILE_ID);
        CMS.debug("RenewalSubmitter: renewal original profileId=" + profileId);

        String aidString = origReq.getExtDataInString(IRequest.AUTHORITY_ID);

        Integer origSeqNum = origReq.getExtDataInInteger(IEnrollProfile.REQUEST_SEQ_NUM);
        IProfile profile = ps.getProfile(profileId);
        if (profile == null) {
            CMS.debug(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(profileId)));
            throw new EBaseException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND",
                    CMSTemplate.escapeJavaScriptStringHTML(profileId)));
        }
        if (!ps.isProfileEnable(profileId)) {
            CMS.debug("RenewalSubmitter: Profile " + profileId + " not enabled");
            throw new BadRequestDataException("Profile " + profileId + " not enabled");
        }

        IProfileContext ctx = profile.createContext();

        if (aidString != null)
            ctx.set(IEnrollProfile.REQUEST_AUTHORITY_ID, aidString);

        IProfileAuthenticator authenticator = renewProfile.getAuthenticator();
        IProfileAuthenticator origAuthenticator = profile.getAuthenticator();

        if (authenticator != null) {
            CMS.debug("RenewalSubmitter: authenticator " + authenticator.getName() + " found");
            setCredentialsIntoContext(request, credentials, authenticator, ctx);
        }

        // for renewal, this will override or add auth info to the profile context
        if (origAuthenticator != null) {
            CMS.debug("RenewalSubmitter: for renewal, original authenticator " + origAuthenticator.getName()
                    + " found");
            setCredentialsIntoContext(request, credentials, origAuthenticator, ctx);
        }

        // for renewal, input needs to be retrieved from the orig req record
        CMS.debug("processRenewal: set original Inputs into profile Context");
        setInputsIntoContext(origReq, profile, ctx, locale);
        ctx.set(IEnrollProfile.CTX_RENEWAL, "true");
        ctx.set("renewProfileId", renewProfileId);
        ctx.set(IEnrollProfile.CTX_RENEWAL_SEQ_NUM, origSeqNum.toString());

        // for ssl authentication; pass in servlet for retrieving
        // ssl client certificates
        SessionContext context = SessionContext.getContext();
        context.put("profileContext", ctx);
        context.put("sslClientCertProvider", new SSLClientCertProvider(request));
        CMS.debug("RenewalSubmitter: set sslClientCertProvider");
        if (origSubjectDN != null)
            context.put("origSubjectDN", origSubjectDN);

        // before creating the request, authenticate the request
        IAuthToken authToken = null;
        Principal principal = request.getUserPrincipal();
        if (principal instanceof PKIPrincipal)
            authToken = ((PKIPrincipal) principal).getAuthToken();
        if (authToken == null)
            authToken = authenticate(request, origReq, authenticator, context, true, credentials);

        // authentication success, now authorize
        authorize(profileId, renewProfile, authToken);

        ///////////////////////////////////////////////
        // create and populate requests
        ///////////////////////////////////////////////
        startTiming("request_population");
        IRequest[] reqs = profile.createRequests(ctx, locale);
        populateRequests(data, true, locale, origNotAfter, origSubjectDN, origReq, profileId, profile, ctx,
                authenticator, authToken, reqs);
        endTiming("request_population");

        ///////////////////////////////////////////////
        // submit request
        ///////////////////////////////////////////////
        String errorCode = submitRequests(locale, profile, authToken, reqs);
        String errorReason = null;

        List<String> errors = new ArrayList<String>();
        if (errorCode != null) {
            for (IRequest req : reqs) {
                String error = req.getError(locale);
                if (error != null) {
                    String code = req.getErrorCode(locale);
                    errors.add(codeToReason(locale, code, error, req.getRequestId()));
                }
            }
            errorReason = StringUtils.join(errors, '\n');
        }

        HashMap<String, Object> ret = new HashMap<String, Object>();
        ret.put(ARG_REQUESTS, reqs);
        ret.put(ARG_ERROR_CODE, errorCode);
        ret.put(ARG_ERROR_REASON, errorReason);
        ret.put(ARG_PROFILE, profile);

        CMS.debug("RenewalSubmitter: done serving");
        endTiming("enrollment");

        return ret;
    } finally {
        SessionContext.releaseContext();
        endAllEvents();
    }
}

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 ww . jav  a2 s .c om
        // ------------------------------------------------------------------
        // 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() + "]");
    }
}