j2ee filters

Hi all,

I have a filter that checks if a user is logged in to the system. I am checking for a flag in the session. I tested on individual pages and it works.

My question has to do with the url pattern:

<filter-mapping>
    <filter-name>AccessFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

The above says that the filter should filter everything. What would the url pattern be if I want the filter to EXCLUDE welcome.jsp, index.htm.

Thanks.
Al
asprin_nycAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TimYatesCommented:
Check in the filter if it is welcome.jsp or index.htm that it's being called with...if so, just chain to the next one...
0
rrzCommented:
I don't think you can exclude anything in the filter.  
You could use  
String referer = request.getHeader("Referer");
and test if referer is not  welcome page.
0
asprin_nycAuthor Commented:
Tim,

Right now I only have one filter. it is doing something like

            if(!req.getRequestURI().equals("/welcome.jsp"))
            {
                if(flag == null)
                {
                    res.sendRedirect("/welcome.jsp");
                }
                else
                {
                    res.sendRedirect(req.getRequestURI());
                }
            }
            else //xxx
            {
                res.sendRedirect("/welcome.jsp");
            }

so what will happend is that it will go into an infinite loop. If i leave out the xxx else block it only shows a blank page, if i do that it will go into an infinite loop. how should i proceed?

thx
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

TimYatesCommented:
           if(!req.getRequestURI().equals("/welcome.jsp"))
            {
                if(flag == null)
                {
                    res.sendRedirect("/welcome.jsp");
                }
                else
                {
                   chain.doFilter( request, response ) ;
                }
            }
            else //xxx
                chain.doFilter( request, response ) ;
0
TimYatesCommented:
Assuming that's inside doFilter;

public void doFilter( final ServletRequest request, final ServletResponse response, FilterChain chain )
0
rrzCommented:
I think Tim and I are suggesting the same thing. Something like the following.  

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
       HttpServletRequest req =  (HttpServletRequest)request;
       String referer = req.getHeader("Referer");
       if(!referer.equals("welcome.jsp") && !referer.equals("index.jsp")){
                // do your filtering here
       }else{chain.doFilter(req,response);}
}
0
TimYatesCommented:
> I think Tim and I are suggesting the same thing

Yup :-)
0
rrzCommented:
I guess Tim has the better method (using getRequestURI()).
But you will have to cast type as I posted.
0
asprin_nycAuthor Commented:
Tim,

I did as suggested but when you do chain.doFilter, the filter is getting called several times. welcome.jsp has the username/password boxes and those get passed to a servlet to do the login which will set the flag in the session. chain.doFilter is calling the filter several times, as a result the parameters are no longer there,

thx
0
rrzCommented:
Please try this  
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
       HttpServletRequest req =  (HttpServletRequest)request;
       String referer = req.getHeader("Referer");
       String uri = req.getRequestURI();
       if(!referer.equals("welcome.jsp") || !uri.equals("/welcome.jsp")){
              if(flag == null)
                             {
                              response.sendRedirect("/welcome.jsp");
                             }
                else
                    {
                      chain.doFilter( request, response ) ;
                    }    
       }else{chain.doFilter(req,response);}
}

But maybe you should look at what kennethxu suggests.  
http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_20397409.html
0
rrzCommented:
I forgot to cast response.
 
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
       HttpServletRequest req =  (HttpServletRequest)request;
       HttpServletResponse resp = (HttpServletResponse)response;
       String referer = req.getHeader("Referer");
       String uri = req.getRequestURI();
       if(!referer.equals("welcome.jsp") || !uri.equals("/welcome.jsp")){
              if(flag == null)
                             {
                              resp.sendRedirect("/welcome.jsp");
                             }
                else
                    {
                      chain.doFilter( request, response ) ;
                    }    
       }else{chain.doFilter(req,resp);}
}

But maybe you should look at what kennethxu suggests.  
http://www.experts-exchange.com/Web/Web_Languages/JSP/Q_20397409.html
0
kennethxuCommented:
try out this:
           if(!req.getServletPath().startsWith("/welcome.jsp"))
            {
                if(flag == null)
                {
                    res.sendRedirect( res.encodeRedirectURL( req.getContextPath() + "/welcome.jsp") );
                }
                else
                {
                   chain.doFilter( request, response ) ;
                }
            }
            else //xxx
                chain.doFilter( request, response ) ;
0
rrzCommented:
One more try, with Tim's and kenneth's suggestions.
 
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
       HttpServletRequest req =  (HttpServletRequest)request;
       HttpServletResponse resp = (HttpServletResponse)response;
       String referer = req.getHeader("Referer");
       String uri = req.getRequestURI();
       StringBuffer url = req.getRequestURL();
       String contextURL = url.substring(0,url.lastIndexOf(req.getServletPath()));
       if(!referer.equals(contextURL + "/welcome.jsp") || !uri.equals("/welcome.jsp")){
              if(flag == null)
                             {
                              resp.sendRedirect( res.encodeRedirectURL( req.getContextPath()
                                                                        + "/welcome.jsp");
                             }
                else
                    {
                      chain.doFilter( request, response ) ;
                    }    
       }else{chain.doFilter(req,resp);}
}
0
kennethxuCommented:
rrz, I could be wrong  but here are my 2 cents:
the referer in http header is full url including protocol, servername. it can never equals to contextURL + "/welcome.jsp".
and when you use refer, you meant any page that is linked (refered) from welcome.jsp can bypass the security check. further, I can create a welcome.jsp page in my server and embed links to asprin_nyc's server, so I can bypass the security check.
I think the referer header is added by client browser and should never be trusted, especially for security purpose.
0
asprin_nycAuthor Commented:
kenneth,

thx for the input I will try your suggestion in a few.
Will let you all know the outcome.

thx.
Al
0
rrzCommented:
Thanks kenneth, maybe that is a dumb idea.    

> the filter is getting called several times. welcome.jsp has the username/password boxes and those get passed to a servlet to do the login which will set the flag in the session.      
So, we will have to exclude the login servlet as well.  

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
                   throws ServletException, IOException {
       HttpServletRequest req =  (HttpServletRequest)request;
       HttpServletResponse resp = (HttpServletResponse)response;
       if(!req.getServletPath().startsWith("/welcome.jsp")
          || !req.getServletPath().startsWith("/LoginServlet")){
              if(flag == null){
                              resp.sendRedirect( resp.encodeRedirectURL( req.getContextPath()
                                                                        + "/welcome.jsp");
              }
                else
                    {
                      chain.doFilter( req, resp ) ;
                    }    
       }else{chain.doFilter(req,resp);}
}
0
rrzCommented:
Of course you could move login and flag setting into your filter and forget about the servlet.
0
rrzCommented:
or let your filter call a login bean.
0
rrzCommented:
One more idea.   You could use  

<filter-mapping>
    <filter-name>AccessFilter</filter-name>
    <url-pattern>filters/secure/*</url-pattern>
  </filter-mapping>  

then you could put your LoginServlet and welcome index page inside the filters folder.
0
rrzCommented:
oops that should be  
  <url-pattern>/filters/secure/*</url-pattern>
0
kennethxuCommented:
>> So, we will have to exclude the login servlet as well
Good catch!
0
rrzCommented:
thanks kenneth, but I really think my last post is the solution.    
0
asprin_nycAuthor Commented:
rrz & kenneth,

I apologize for the delay. I was out for a few days.
In any case I tried your suggestion but when

resp.sendRedirect( resp.encodeRedirectURL( req.getContextPath()
                                                                        + "/welcome.jsp");

executes it brings me back to the same filter. Which means infinite loop.

rrz, I am trying to avoid to move things to a different folder.

thx.
Al
0
rrzCommented:
Please show us your filter code.
0
asprin_nycAuthor Commented:
rrz,


public void doFilter(ServletRequest request,ServletResponse response,
                     FilterChain chain)
            throws java.io.IOException, ServletException
    {
        HttpServletResponse res = (HttpServletResponse)response;
        HttpServletRequest req = (HttpServletRequest)request;

        String flag = null;
        HttpSession session = req.getSession();

        if(session.getAttribute(ApplicationConstants.FLAG)!=null)
        {
            flag = (String)session.getAttribute(ApplicationConstants.FLAG);
        }

        if(!req.getServletPath().startsWith("/welcome.jsp")
           || !req.getServletPath().startsWith("/login.action"))
        {
            if(flag == null)
            {
                res.sendRedirect( res.encodeRedirectURL( req.getContextPath() +
                        "/welcome.jsp"));
            }
            else
            {
                chain.doFilter( req, res ) ;
            }
        }
        else
        {
            chain.doFilter(req,res);
        }
}

thx.
Al
0
rrzCommented:
>("/login.action")  
Does that map to your servlet?  
Did you  try  ?
 !req.getServletPath().startsWith("/login"))  
Maybe you should show us your servlet and servlet mapping elements in your web.xml.
0
kennethxuCommented:
it is because you didn't set the flag.
try out below and make sure
1. you set flag in login.action
2. there is not image/css/js file links in the welcome.jsp page because those links will invoke this filter too!

public void doFilter(ServletRequest request,ServletResponse response,
                     FilterChain chain)
            throws java.io.IOException, ServletException
    {
        HttpServletResponse res = (HttpServletResponse)response;
        HttpServletRequest req = (HttpServletRequest)request;

        String flag = null;
        HttpSession session = req.getSession();

        if(session.getAttribute(ApplicationConstants.FLAG)!=null)
        {
            flag = (String)session.getAttribute(ApplicationConstants.FLAG);
        }

        if(!req.getServletPath().startsWith("/welcome.jsp")
           || !req.getServletPath().startsWith("/login.action"))
        {
            if(flag == null)
            {
                res.sendRedirect( res.encodeRedirectURL( req.getContextPath() +
                        "/welcome.jsp"));
            }
            else
            {
                chain.doFilter( req, res ) ;
            }
        }
        else
        {
            res.sendRedirect( res.encodeRedirectURL( req.getContextPath() +
                        "/login.action"));
        }
}
0
kennethxuCommented:
sorry, forget about my previously posted code. use this code:

public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
      throws java.io.IOException, ServletException
{
        HttpServletResponse res = (HttpServletResponse)response;
        HttpServletRequest req = (HttpServletRequest)request;

        HttpSession session = req.getSession();
      String flag = (String)session.getAttribute(ApplicationConstants.FLAG);

        if(flag != null || req.getServletPath().startsWith("/welcome.jsp") || req.getServletPath().startsWith("/login.action") )
        {
          chain.doFilter( req, res ) ;
        }
        else
        {
          res.sendRedirect( res.encodeRedirectURL( req.getContextPath() + "/welcome.jsp" ) );

        }
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
asprin_nycAuthor Commented:
All,

I just changed

if( !req.getServletPath().startsWith("/welcome.jsp")
           && !req.getServletPath().startsWith("/login.action"))

it should be &&

thx.
Al
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.