title: JSF login with credentials in request
body: <p>I'm developing a web application with JSF 2.0. I implemented login through a managed bean (LoginHandler) and check if the user is logged in with a filter.</p>
  
  <p>Now I got the request to be able to login to the application by sending a request with username and password as parameters. Which is the best way to do that?</p>
  
  <p>I tried using f:metadata and a preRenderView event, but it seems a filter is the better solution? I also tried writing an HTTPFilter on url of the login page, but the problem is I need to store user data in my managed bean, and when I first access the application I don't have a session from which to get my manage bean.</p>
  
  <p><em>Otpion 1: f:metadata and action in managedbean LoginHandler</em>:
  on login page:</p>
  
  <pre><code>&lt;f:metadata&gt;
      &lt;f:viewParam name="username" value="#{loginManager.username}"/&gt;
      &lt;f:viewParam name="password" value="#{loginManager.password}"/&gt;
      &lt;f:event type="preRenderView" listener="#{loginManager.singleSignOn}"/&gt;            
  &lt;/f:metadata&gt;
  </code></pre>
  
  <p>The method singleSignOn in LoginHandler checks if username and password are set. If that's the case, it does the same logic as submitting the login form (it calles the same method), and if the login is successful, it forwards to the welcome page. Otherwise it returns null (and the login page is displayed)</p>
  
  <p><em>Otpion 2: filter</em>:</p>
  
  <pre><code>public void doFilter(ServletRequest req, ServletResponse res,
          FilterChain chain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest) req;
      HttpServletResponse response = (HttpServletResponse) res;
      HttpSession session = request.getSession(false);
  
      String username = request.getParameter("username");
      String password = request.getParameter("password");
  
      LoginHandler loginHandler = null;
      if (session != null) {
          loginHandler = (LoginHandler) session.getAttribute("loginHandler");
  
          if (loginHandler != null &amp;&amp; username != null &amp;&amp; password != null) {
              boolean loginOk = false;
              //do logic using methods and objects in loginHandler and set loginOk if login is successful
              loginOk = loginHandler.login(username, password);
              if (loginOk) {
                  // login OK
                  response.sendRedirect(request.getContextPath() + WELCOME_PAGE_URL);
              }
          }
      }
  
      chain.doFilter(request, response);
  }
  </code></pre>
  
  <p>As said, option 2 has the problem that session isn't set the first time I access the application (i.e., i need to try to login twice - the second time everything works)</p>
  
  <p>Thanks</p>
  
  <p>EDIT1: updated comment and description to better reflect the role of the class LoginHandler</p>