enable realm in Tomcat 7 server.xml

Posted on November 4, 2012. Filed under: java/j2EE |


Let’s follow tomcat 7 document and create a realm that protects a web application named test-app

(http://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html#Quick_Start)

The following is an example configuration in Tomcat 7 with MemoryRealm as the default realm. Assuming you have enabled SSL in Tomcat 7 server.xml.

Open <tomcat_home>/conf/server.xml and uncomment or add the following line.

<Realm className=”org.apache.catalina.realm.MemoryRealm” />

Open <tomcat_home>/conf/tomcat-users.xml to set the role and user/password.

— tomcat-users.xml —

<?xml version=”1.0″ encoding=”UTF-8″?>

<tomcat-users>

<role rolename=”appadmin”/>

<user username=”testapp” password=”test” roles=”appadmin”/>

</tomcat-users>

Open <project_home>/test-app/WebContent/WEB-INF/web.xml and add the

<security-constraint> and <login-config>:

— web.xml —

<web-app version=”3.0″

xmlns=”http://java.sun.com/xml/ns/javaee&#8221;

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”&gt;

<security-constraint>

<web-resource-collection>

<web-resource-name>test-app</web-resource-name>

<url-pattern>/hello</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>appadmin</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>test-app-realm</realm-name>

</login-config>

</web-app>

The protected web-resource is:

— HelloWorld.java —

package testPackage;

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

import javax.servlet.http.*;

@WebServlet(“/hello”)

public class HelloWorld extends HttpServlet {

@Override

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println(“Hello World Secure J2EE/Java Lab”);

}

}

Now open browser, visit the following link,

https://localhost:8443/test-app/hello

A popup window will asking for user/password, only if you input the testapp/test as user/pass, you will be able to access the web resource. Canceling will result in status 401 error.

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: