tags:

views:

601

answers:

3

I created a filter to prevent the user by typing the url to access certain page. I have 3 page, the user supposed to access page2 or page3 only through page1. First page required the user enter username, den go to page2 and so on. I have a managed bean user scoped session.This is my filter method. The problem is that when i never enter the username this line (req.getAttribute("user") == null) wont give me null but something value like this bean.User@6ed322. Anyone can help correct me where goes wrong ?

public void doFilter(ServletRequest request, ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
 HttpServletRequest req = (HttpServletRequest) request;
 HttpServletResponse resp = (HttpServletResponse) response;
 HttpSession httpSession = req.getSession(false);
 String pageRequested = req.getRequestURI().toString();

 if (httpSession == null) {
  httpSession = req.getSession(true);
  resp.sendRedirect("Page1.faces");
 } else if (httpSession.getAttribute("user") != null
   && ((User) httpSession.getAttribute("user")).getUsername() == null
   && !pageRequested.contains("Page1.faces")) {
  resp.sendRedirect("Page1.faces");
 } else {
  chain.doFilter(request, response);
 }
}
+1  A: 

So, ... you want to prevent access to certain pages when the user has not logged in correctly? Then you should investigate Spring security or JAAS for catching page access and redirecting to login pages. You could as an alternative set an attribute in the session for good logins and check that in your filter.

Martlark
A: 

Close your browser / clear your sessions/cookies before any subsequent attempts. Also you can make a logout button that makes session.invalidate().
Spring security or JAAS may be a big overhead for you, but you can use a JSF PhaseListener, instead of a filter, and do your checks on the RENDER_RESPONSE phase, for example.

Bozho
A: 

I have a managed bean user scoped session.

Is this declared in faces-config.xml? Is this referenced in any of the JSF pages?

If so, then JSF would create automatically one for you. You shouldn't intercept on that. Either remove the declaration from faces-config.xml or change the way you check the logged-in user.

If not, then your testing methodology is poor. To get a new session at the client side either restart the client application or do a HttpSession#invalidate() at the server side (which is in my opinion a bit too disastrous, just removing or nulling the user attribute from the session should suffice).

BalusC