A - Java EE Container Managed Authentication
B - Homegrown a Servlet Filter
C - 3rd Party Java EE Authentication Frameworks
While I was searching the right solution, I worked on small examples on JSF 2.x, Tomcat 7.0 and Hibernate. One of them was developed based on container managed authentication. I think that this solution is the easiest to implement on Web applications. There are five steps to adapt this solution into your application;
1) Configure server.xml on the Tomcat directory;
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/authentication_db"
connectionName="..." connectionPassword="..."
userTable="user" userNameCol="USER_NAME" userCredCol="PASSWORD"
userRoleTable="usergroup" roleNameCol="USER_GROUP_NAME" />
2) Create entities (User and User Group) based on JDBCRealm implementation on the link - https://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html#Standard_Realm_Implementations.
3) Not to forget updating hibernate mapping files of entities based on changes on entities after Step-2. JDBCRealm Implementation needs many-to-many relationship between User and User Group tables, that's why related tags on mapping files should be configured properly.
4) Configure web.xml file;
<security-constraint>
<display-name>Restricted</display-name>
<web-resource-collection>
<web-resource-name>Restricted Area</web-resource-name>
<url-pattern>/authorized/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.xhtml</form-login-page>
<form-error-page>/login.xhtml</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>user</role-name>
</security-role>
5) Lastly, create your login function;
public String login(){
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try {
//Login via the Servlet Context
request.login(getLoginName(), getLoginPass());
return "success";
} catch (ServletException e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Login", null));
e.printStackTrace();
}
return "failure";
}
Optimization can be made based on reqirements of an application, but the development-process will be similar I present above for container managed authentication.