Friday, August 20, 2010

HTTP Basic Authentication

Basic authentication is defined by the HTTP/1.1 specification. It is very simple HTTP authentication method. When a client attempts to access a protected web resource, the web container activates the HTTP authentication mechanism that has been configured for that resource and the server prompts for a username and password. If the server will be able to authenticate client, then provides access to the resource otherwise the it will not be granted access to the resource and the process repeats.

HTTP basic authentication is not particularly secure. It sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.

Basic authentication follows the steps below
1. An attempt is made to access a protected JSP page—/protected-page.jsp.

Example JSP page /protected-page.jsp:
<html><head><title>A Protected Page</title></head>
<body>
<p>
User principal: <%= request.getUserPrincipal().getName() %>.<br/>
User name: <%= request.getRemoteUser() %>.<br/>
Request Authenticated with: <%= request.getAuthType() %>.<br/>
</p>
<p>
<% if(request.isUserInRole("role1")) { %>
You are in role1<br/>
<% } else {%>
You are not in role2<br/>
<% } %>

<% if(request.isUserInRole("role2")) { %>
You are in role2<br/>
<% } else {%>
You are not in role1<br/>
<% } %>
</p>
</body>
</html>

The client is presented with a dialog box asking for name and password. The client submits the user name and password to the server. After authentication, the JSP page is displayed.

2. The protected JSP page is specified as a protected resource in the application's deployment descriptor file, web.xml. Also, specified BASIC as the authentication method and page is only accessed by role1 and role2.

Example deployment descriptor /WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>

<security-constraint>

<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>

<auth-constraint>

<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Basic Authentication Example</realm-name>
</login-config>
</web-app>


3. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,

<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>

4. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.

Hope this is useful! Enjoy!

No comments:

Post a Comment