2

I am trying to implement simple log in functionality in a JSF application. Following this answer, I have implemented an AuthenticationFilter. I am trying to set an object in my managed bean as :

FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("user", user);

doFilter method of AuthenticationFilter looks like this:

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

       if (((HttpServletRequest) req).getSession().getAttribute("user") == null){   
            ((HttpServletResponse) resp).sendRedirect("../login.jsf");

       } else {
         chain.doFilter(req, resp);
       }
   }

I always get ((HttpServletRequest) req).getSession().getAttribute("user") == null (true). I have searched and applied many alternatives like (in my bean) :

facesContext.getExternalContext().getSessionMap().put("user", user);
request.getSession().setAttribute("user", user);
session.getServletContext().setAttribute("user", user); // DISASTER 

I don't have a clue how to manage this thing. Seemingly duplicate question did'nt help either. What am I doing wrong? How can I make it work? Is there a good and clean way to do it using JSF capabilities?

Community
  • 1
  • 1
Umer Hayat
  • 1,993
  • 5
  • 31
  • 58
  • Is the `JSESSIONID` cookie properly maintained across requests by the browser? Track the HTTP traffic. – BalusC Jun 15 '12 at 12:23

1 Answers1

2

I recommend you use a security library like the previous answer. There are too many ways to do this incorrectly...

But if you're dead set on doing it yourself, don't set this in the Session. Declare a ManagedBean and scope it as the session level. Have a property of the bean be the username.

Jonathan S. Fisher
  • 8,189
  • 6
  • 46
  • 84