12/31/2010

Simple webapp with BASIC authentication

To enable BASIC authentication in a webapp, one needs to
(1) configure roles and other security aspects in web.xml;

(2) administratively create the users in application server; and

(3) map the roles declared in step 1 to users created in step 2, with appserver-specific descriptor.

The following is a simple webapp that only contains 3 files: TestServlet class, web.xml, sun-web.xml.

package test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello from " + getServletName());
}

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>

<security-constraint>
<web-resource-collection>
<web-resource-name>secure</web-resource-name>
<url-pattern>/TestServlet</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>tester</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>file</realm-name>
</login-config>

<security-role>
<role-name>tester</role-name>
</security-role>
</web-app>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
<sun-web-app>
<security-role-mapping>
<role-name>tester</role-name>
<principal-name>joe</principal-name>
<group-name>user</group-name>
</security-role-mapping>
</sun-web-app>
To create the user in GlassFish:
$ $GLASSFISH_HOME/bin/asadmin create-file-user --group user joe
Compile TestServlet class and jar up *.class and *.xml into a test.war:
WEB-INF/classes/test/TestServlet.class
WEB-INF/sun-web.xml
WEB-INF/web.xml
Copy it to $GLASSFISH_HOME/domains/domain1/autodeploy directory to deploy it. To run it go to the url http://localhost:8080/test/TestServlet. After entering the username and password, the following response is displayed:
Hello from TestServlet