Jarrett
Jarrett

Reputation: 1778

HttpServletRequestWrapper removed parameter still showing up

I'm trying to filter out a query parameter named 'reason' using a Filter in java/jsp.

Basically, the filter is in place to ensure that a user has entered a 'reason' for viewing a page. If they have not, it needs to redirect them to the 'enter reason' page. Once they have entered a valid reason, they can continue on to the page they requested.

So the basics of it work. However, the 'reason' is sent via a query paremter (i.e. GET parameter). Once the user selects a reason, the reason parameter is being forwarded on to the page they wanted to see. This is a problem, since checking if the reason paremeter exists is one of the main ways the filter determines if the user can move on.

I've tried extending HttpServletRequestWrapper, and overrode a bunch of methods (i.e. getPameter, etc) in an effort to remove the 'reason' parameter. However, I haven't been able to see the parameter get removed. Once the Filter forwards on to the requested page, the 'reason' parameter is always in the query string (i.e. the url in the browser url bar) as a GET parameter.

My filter class looks like:

public final class AccessRequestFilter implements Filter {

    public class FilteredRequest extends HttpServletRequestWrapper {

        public FilteredRequest(ServletRequest request) {
            super((HttpServletRequest)request);
        }

        @Override
        public String getParameter(String paramName) {
            String value = super.getParameter(paramName);

            if ("reason".equals(paramName)) {
                value = null;
            }

            return value;
        }

        @Override
        public String[] getParameterValues(String paramName) {
            String[] values = super.getParameterValues(paramName);

            if ("reason".equals(paramName)) {
                values = null;
            }

            return values;
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(getParameterMap().keySet());
        }

        @Override
        public Map<String, String[]> getParameterMap() {            
            Map<String, String[]> params = new HashMap<String, String[]>();
            Map<String, String[]> originalParams = super.getParameterMap();

            for(Object o : originalParams.entrySet()) {
                Map.Entry<String, String[]> pairs = (Map.Entry<String, String[]>) o;
                params.put(pairs.getKey(), pairs.getValue());
            }

            params.remove("reason");

            return params;
        }

        @Override
        public String getQueryString() {
            String qs = super.getQueryString();

            return qs.replaceAll("reason=", "old_reason=");
        }

        @Override
        public StringBuffer getRequestURL() {
            String qs = super.getRequestURL().toString();

            return new StringBuffer( qs.replaceAll("reason=", "old_reason=") );
        }
    }

    private FilterConfig filterConfig = null;  
    private static final Logger logger = MiscUtils.getLogger();

    public void init(FilterConfig filterConfig) throws ServletException {  
        this.filterConfig = filterConfig;  
    }  

    public void destroy() {  
        this.filterConfig = null;  
    }  

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
        logger.debug("Entering AccessRequestFilter.doFilter()");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();

        boolean canView = false;
        long echartAccessTime = 0L;
        String demographicNo = "";
        String reason = "";
        Date current = new Date();

        String user_no = (String) session.getAttribute("user");

        ProgramProviderDAO programProviderDAO = (ProgramProviderDAO)SpringUtils.getBean("programProviderDAO");
        ProgramQueueDao programQueueDao = (ProgramQueueDao)SpringUtils.getBean("programQueueDao");

        // Check to see if user has submitted a reason
        reason = request.getParameter("reason");
        demographicNo = request.getParameter("demographicNo");
        Long demographicNoAsLong = 0L;
        try {
            demographicNoAsLong = Long.parseLong( demographicNo );
        } catch (Exception e) {
            logger.error("Unable to parse demographic number.", e);
        }

        if (reason == null) {
            // If no reason was submitted, see if user still has time remaining on previous submission (if there was one)
            try {
                echartAccessTime = (Long)session.getServletContext().getAttribute("echartAccessTime_" + demographicNo);
            } catch (Exception e) {
                logger.warn("No access time found");
            }

            if (current.getTime() - echartAccessTime < 30000) {
                canView = true;
            }
        } else if (!reason.equals("")) {
            // TODO: validate reason
            canView = true;
            session.getServletContext().setAttribute("echartAccessTime_" + demographicNo, current.getTime());
            String ip = request.getRemoteAddr();
            // Log the access request and the reason given for access
            LogAction.addLog(user_no, "access", "eChart", demographicNo, ip, demographicNo, reason);
        }

        if (!canView) {
            // Check if provider is part of circle of care
            List<Long> programIds = new ArrayList<Long>();

            List<ProgramQueue> programQueues = programQueueDao.getAdmittedProgramQueuesByDemographicId( demographicNoAsLong );
            if (programQueues != null && programQueues.size() > 0) {
                for (ProgramQueue pq : programQueues) {
                    programIds.add( pq.getProgramId() );
                }

                List<ProgramProvider> programProviders = programProviderDAO.getProgramProviderByProviderProgramId(user_no, programIds);

                if (programProviders != null && programProviders.size() > 0) {
                    canView = true;
                }
            }
        }

        String useNewCaseMgmt;
        if((useNewCaseMgmt = request.getParameter("newCaseManagement")) != null ) {     
            session.setAttribute("newCaseManagement", useNewCaseMgmt); 
            ArrayList<String> users = (ArrayList<String>)session.getServletContext().getAttribute("CaseMgmtUsers");
            if( users != null ) {
                users.add(request.getParameter("providerNo"));
                session.getServletContext().setAttribute("CaseMgmtUsers", users);
            }
        }
        else {
            useNewCaseMgmt = (String)session.getAttribute("newCaseManagement");             
        }

        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();

        if (!canView && !requestURI.startsWith(contextPath + "/casemgmt/accessRequest.jsp")) {
            httpResponse.sendRedirect(contextPath + "/casemgmt/accessRequest.jsp?" + httpRequest.getQueryString());
            return;
        }

        logger.debug("AccessRequestFilter chainning");
        chain.doFilter( new FilteredRequest(request), response);
    }
}

The filter is setup to intercept all request and forwards coming into a subdirectory called casemgmt. The filter in web.xml is like:

<filter>
        <filter-name>AccessRequestFilter</filter-name>
        <filter-class>org.oscarehr.casemgmt.filter.AccessRequestFilter</filter-class>
    </filter>
...
<filter-mapping>
        <filter-name>AccessRequestFilter</filter-name>
        <url-pattern>/casemgmt/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

Anyone have any ideas how I can actually remove the 'reason' parameter?

Upvotes: 1

Views: 7651

Answers (1)

BalusC
BalusC

Reputation: 1109132

Wrapping and manipulating the HttpServletRequest in the server side absolutely doesn't magically affect the URL as you see in browser's address bar. That URL stands as-is, as it's the one which the browser used to request the desired resource. The wrapped request would only affect the server side code which is running after the filter on the same request.

If you want to change the URL in browser's address bar, then you should be sending a redirect to exactly the desired URL.

Basically,

if (reasonParameterIsIn(queryString)) {
    response.sendRedirect(requestURL + "?" + removeReasonParameterFrom(queryString));
    return;
}

Upvotes: 2

Related Questions