Authentication mechanism allows users to have secure access to the application by validating the username and password. We will be using JSF view for login, DAO object ,HttpSession for session management, JSF managed bean and mysql database. Lets now look in detail as how to create a JSF login logout authentication mechanism in JSF application. Step 1: Create the table Users in mysql database as
CREATE TABLE Users(
uid int(20) NOT NULL AUTO_INCREMENT,
uname VARCHAR(60) NOT NULL,
password VARCHAR(60) NOT NULL,
PRIMARY KEY(uid));
Here we create user table with uid as the primary key, username and password fields with not null constraints. Step 2: Insert data into the table Users as;
INSERT INTO Users VALUES(1,'adam','adam');
Before we move on to our project related code, below image shows the project structure in Eclipse. Just create a dynamic web project and convert it to maven to get the project stub and then keep on adding different components. Step 3: Create the JSF login page
login.xhtml
as;
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:h="https://java.sun.com/jsf/html">
<h:head>
<title>login</title>
</h:head>
<h:body>
<h:form>
<h3>JSF Login Logout</h3>
<h:outputText value="Username" />
<h:inputText id="username" value="#{login.user}"></h:inputText>
<h:message for="username"></h:message>
<br></br><br></br>
<h:outputText value="Password" />
<h:inputSecret id="password" value="#{login.pwd}"></h:inputSecret>
<h:message for="password"></h:message>
<br></br><br></br>
<h:commandButton action="#{login.validateUsernamePassword}"
value="Login"></h:commandButton>
</h:form>
</h:body>
</html>
Here we are creating a JSF login view page with username and password fields and set values for these fields through the login managed bean. We invoke the validateUsernamePassword
method on click of Login button to validate the username and password. Step 4: Create the managed bean Login.java
as;
package com.journaldev.jsf.beans;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.journaldev.jsf.dao.LoginDAO;
import com.journaldev.jsf.util.SessionUtils;
@ManagedBean
@SessionScoped
public class Login implements Serializable {
private static final long serialVersionUID = 1094801825228386363L;
private String pwd;
private String msg;
private String user;
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
//validate login
public String validateUsernamePassword() {
boolean valid = LoginDAO.validate(user, pwd);
if (valid) {
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
return "admin";
} else {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd",
"Please enter correct username and Password"));
return "login";
}
}
//logout event, invalidate session
public String logout() {
HttpSession session = SessionUtils.getSession();
session.invalidate();
return "login";
}
}
We declare three String variables user, pwd and msg for username, password and error message fields along with the getter and setter methods. We write a method validateUsernamePassword()
for validating the username and password field by invoking the LoginDAO
class to fetch the username and password from the database and compare it with the front end values passed. If the username and password does not match an error message is displayed as “Incorrect username and password” . Also a logout()
method is written to perform logout by invalidating HTTPSession attached. Step 5: Now create the LoginDAO java class as below. Note that database operations code is not optimized to be used in a real project, I wrote it as quickly as possible because the idea is to learn authentication in JSF applications.
package com.journaldev.jsf.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.journaldev.jsf.util.DataConnect;
public class LoginDAO {
public static boolean validate(String user, String password) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DataConnect.getConnection();
ps = con.prepareStatement("Select uname, password from Users where uname = ? and password = ?");
ps.setString(1, user);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
//result found, means valid inputs
return true;
}
} catch (SQLException ex) {
System.out.println("Login error -->" + ex.getMessage());
return false;
} finally {
DataConnect.close(con);
}
return false;
}
}
In the validate()
method we first establish connection to the database by invoking the DataConnect
class getConnection
method. We use PreparedStatement
to build the query to fetch the data from the database with the user entered values. If we get any data in result set, it means input is valid and we return true, else false. Step 6: Create the DataConnect.java
class as;
package com.journaldev.jsf.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DataConnect {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/cardb", "pankaj", "pankaj123");
return con;
} catch (Exception ex) {
System.out.println("Database.getConnection() Error -->"
+ ex.getMessage());
return null;
}
}
public static void close(Connection con) {
try {
con.close();
} catch (Exception ex) {
}
}
}
We load the JDBC driver using Class.forName
method and use DriverManager.getConnection
method passing the url, username and password to connect to the database. Step 7: Create SessionUtils.java to obtain and manage session related user information.
package com.journaldev.jsf.beans;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionUtils {
public static HttpSession getSession() {
return (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
}
public static HttpServletRequest getRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
}
public static String getUserName() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
return session.getAttribute("username").toString();
}
public static String getUserId() {
HttpSession session = getSession();
if (session != null)
return (String) session.getAttribute("userid");
else
return null;
}
}
Here we obtain a session for each user logged through the getUserId method thereby associating a session id to a particular user id. Step 8: Create the authorization filter class as;
package com.journaldev.jsf.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthorizationFilter implements Filter {
public AuthorizationFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest reqt = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession ses = reqt.getSession(false);
String reqURI = reqt.getRequestURI();
if (reqURI.indexOf("/login.xhtml") >= 0
|| (ses != null && ses.getAttribute("username") != null)
|| reqURI.indexOf("/public/") >= 0
|| reqURI.contains("javax.faces.resource"))
chain.doFilter(request, response);
else
resp.sendRedirect(reqt.getContextPath() + "/faces/login.xhtml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void destroy() {
}
}
We implement the standard filter class by overriding the destroy and doFilter methods. In the doFilter method we will redirect user to login page if he tries to access other page without logging in. Step 9: Create admin.xhtml
as;
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
xmlns:h="https://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p>Welcome #{login.user}</p>
<h:commandLink action="#{login.logout}" value="Logout"></h:commandLink>
</h:form>
</h:body>
</html>
This page is rendered when the user logs in successfully. Logout functionality is implemented by calling the logout method of the Login.java
class. Step 10: Create faces-config.xml
file as;
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="https://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee
https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>admin</from-outcome>
<to-view-id>/admin.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Once done with all the steps specified above run the application and see the following output in the browser. Login Page Authentication Error Page
Login Success Page
Accessing admin.xhtml while logged in
Just click on the Logout link and the session will be invalidated, after that try to access admin.xhtml page and you will be redirected to the login page, go ahead and download the project from below link and try it out.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Can I use this to show parts of a web site? Content logged users is secure? or render param can be inyectable
- Ivan
Can I use this to show parts of a web site?
Content logged users
is secure? or rendered param can be inyectable- Ivan
nice tutorial, however you forgot to specify mappings on web.xml file i.e. AuthorizationFilter *.AuthirizationFilter AuthorizationFilter /secured/*
- akasozi
Can you please provide a complete web.xml example showing the filter mappings? Thanks!
- LogicalDave
Thank’s for this example, I’ve an error in SessionBean, i’m using JSF 2.1, how to import it ?
- Faycal
Thanks, really helped!
- Maor
is it specified which version of JSF is used here ? and what is its jar ?
- Name
Thanks for your tutorial, it was very helpful. is there any way we can use entity class that connect to database? trying not to code the sql statement. Thanks so much
- jacklyn onye
Excellent but I have a question… what happend with AuthorizationFilter
- Boris
Rename the class “SessionBean” in the example immediately. It’s not a bean so the name is confusing.
- Philip Grove
YES. because the clase is named “SessionBean” i have lost time truing to understand what it means.
- daniel
Never ever catch “Exception” in production code, it has loads on unforeseen consequences. I had hoped that it was not done here to promote proper exception handling. Catching “Exception” is sometimes done in the test phase before proper exception handling is done, because proper exception handling on something that might not even work is a waste of time.
- Philip Grove
Upon further investigation of the example it appear to contain code that is never used and code that suggest it has been directly copied from another source. Reveal this source immediately and stop taking credit for the work of others.
- Philip Grove
its not copied from any where, can you explain which part of code is not used. Also it’s just for understanding the concept of authentication in JSF, if I will provide production level coding here, the length of post will be 3 times and it will loose the purpose of article.
- Pankaj
Hello Pankaj I was reading your tutorial and it really gave me some insights,I tried it myself but it does not work.It does not check username and password against the database but passes the values
- Ainsley
Hi you. Thank you so much. But i have any question. In the file faces-config.xml, why not add a code: controller.SercurityFilter And. I can implements PhaseListener instead of implements Filter in the file AuthorizationFilter. Thank you.
- Thien
controller.SercurityFilter
- Thien
very good example. why after logout if you press back button in browser in not invalidated showing the admin page with the name of the logged user? thank you for a reply.
- alfredo fernandes
I think this is a good question. We sould look for that.
- BurakErk
public String logout() { HttpSession session = SessionBean.getSession(); user = “”; pwd = “”; session.invalidate(); return “login”; } This sould work.
- BurakErk
let’s say in the Users table is a field department , how to map this field to the JSF page?
- Askat
The class name “LoginDAO” is misleading as this it not a DAO object at all, it’s just a simple class which contain one (static) method.
- Krzysiek
Really good my friend. Great example
- Alessandro Mattiuzzi
Thanks a lot, so helpful what is JSF managed bean behavior with static method? Is it safe with multiple online user? (conflict sessions or not !!)
- Gholamali Irani
Without any entries to web.xml the AuthorizationFilter is never used. Minimum is to include it in web.xml in follwing manner (replace xxxx with your package name): AuthorizationFilter xxxx.filter.AuthorizationFilter This Filter authorizes user access to application. error_page /error/error.xhtml
- Martin Zwernemann
Sorry, the xml was eaten by your server. I replaced the XML-marks with asterisks: *filter* *filter-name*AuthorizationFilter*/filter-name* *filter-class*xxx.filter.AuthorizationFilter*/filter-class* *description*This Filter authorizes user access to application.*/description* *init-param* *param-name*error_page*/param-name* *param-value*/ui/energy/error/error.xhtml*/param-value* */init-param* */filter*
- Martin Zwernemann
I get an error of java.lang.NullPointerException .How can I fix this ?
- Mustafa Darcan
:-) this question Sound like The Project don´t want run, how to fix it :-)
- zongi
Dear Pankaj, Thanks a lot. The code you provided helped a lot with my project. One question though, how would you exclude a page from authentication. For example, if you want the user to see the home page first, which should have a link to login page. Any suggestions would be immensely appreciated. Ravi
- ravi
An Error Occurred: java.lang.NullPointerException
- Samy
Thanks a lot… =)
- Vitor Da Costa
Perfect! That’s work fine, thank you :)
- Toshyjoe
the app seems great though its throwing an exception “java.lang.NullPointerException” why?
- edward
java.lang.NullPointerException -> You have to add the mysql connector library. It was perfect! That’s work fine, thank you.
- Christian
On HttpSession session = SessionBean.getSession(); i’ve error: “error: cannot find symbol” Can you help me?
- Grzesiek
Actually I changed the class name of SpringBean to SpringUtils and forgot to update the code in Login.java class. I have updated the code in the post as well as project zip file. You can download the project now, it will work fine.
- Pankaj
HELO Pankaj. I am using this proekt. How can download package com.journaldev
- Tavakkaljon Dehqonov
I have a problem with this code, everything works great bu if I try to log in multiple users and then log out only one every users session is killed ? Quite a problem or just me ?
- Hrvoje
Yeah.! I have the same problem… this method kind accept only one Login at time. How to solve it?
- Fabio
thank u :)
- yosser