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.
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?
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.
Otpion 1: f:metadata and action in managedbean LoginHandler: on login page:
<f:metadata>
<f:viewParam name="username" value="#{loginManager.username}"/>
<f:viewParam name="password" value="#{loginManager.password}"/>
<f:event type="preRenderView" listener="#{loginManager.singleSignOn}"/>
</f:metadata>
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)
Otpion 2: filter:
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 && username != null && 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);
}
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)
Thanks
EDIT1: updated comment and description to better reflect the role of the class LoginHandler