I was using form-based authentication as a way to restrict the access to collection of resources in my project, allowing only users that had previously registered a user name and password to reach them. The user names and passwords of such registered users where kept in a database. The context.xml file contained information about this database, so it could be easily retrieved and compared with the input from the user, to verify the user had entered an existing user name and corresponding valid password. This is what is called a Data Source Realm. Here it is declared in the context.xml file.
<Realm className="org.apache.catalina.realm.DataSourceRealm" debug="99" dataSourceName="jdbc/la_carreta" localDataSource="true" userTable="UserPass" userNameCol="Username" userCredCol="Password" userRoleTable="UserRole" roleNameCol="Rolename" />
The authentication worked as expected. Whenever a user tried to access the restricted resource for the first time, a form would display, asking the user to provide a valid user name and password. If the values provided were found in the database, then the user was allowed to access the resource; otherwise, an error page would display.
My problem was that I needed to find out who accessed the resource, so that I could retrieve information about that user such as name, credit card info, etc. After searching for a while, I came across a useful little method of the request object. Thanks to this method, I was able to obtain the user name entered by the user during the previous log in, and then use that user name to retrieve the rest of the information about that particular user from other tables in the database.
String username = request.getUserPrincipal().getName(); UserDao userDao = UserService.getUserDao(); User user = userDao.findUserByUsername(username);