Following on from Setting up role based security in tomcat we now look at accessing the realm security information from code. Although tomcat takes care of authenticating users at the right time, there are still times when we need to programatically access the credential information. For example the following snippet from userProfile.jsp is a mixed mode page In that anyone can view the page, but some users with manager role see more information.
To do this we use a method on the request object. request.isUserInRole(roleName);.
Below is an example of its usage from the userProfile page.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>User Profile</title></head>
<body>
<h1>User Profile</h1>
<p>User name: Dave</p>
<p>Profile: Great Guy!</p>
<%
if(request.isUserInRole("manager"))
{
%>
<p>Phone: 123 5555555</p>
<p>Some other confidential data</p>
<%
}
%>
</body>
</html>
Another method on the request object lets us access the name of the user, or null if the current session is not yet authenticated.
String session.getRemoteUser();
Its also useful to be able to logout the user.
void session.invalidate();
If the database realm we created previously has MD5 digest enabled, then we need to make sure that everytime we write the password that it is encrypted as an MD5 digest. The code below will convert a plaintext password as an MD5 digest. Note again that there is no documented way to get from the digest to the password, so if a user forgets the password it can only be reset.
package com.thecoderscorner.webexample;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Generator
{
public static String generateMD5digest(String plaintext)
throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md_password = plaintext.getBytes();
byte[] md_hash = md.digest(md_password);
String bytes = "";
for(byte by : md_hash)
{
bytes += String.format("%02x", by);
}
return bytes;
}
public static void main(String[] args) throws Exception
{
System.out.println("test = " + generateMD5digest("test"));
}
}
Hopefully this article has given you enough information to get started with role based security, there's a lot more information available on the tomcat site and in several good books, some of which are listed in this article.