Wednesday, March 31, 2010

Basic Authentication with Spring Security (Part 2)

So I double checked my configuration, nothing seems to be wrong.  In the end, I managed to get it to work for the first time with following added configuration:
In web.xml
<login-config>
    <auth-method>BASIC</auth-method>
</login-config>
<error-page>
    <error-code>401</error-code>
    <location>/WEB-INF/jsp/errors/401.jsp</location>
</error-page>
401.jsp
<%
  response.setHeader("WWW-Authenticate", "BASIC realm=\"My Realm\"");
%>
<html>
    <head>
        <meta http-equiv="refresh" content="1;url=https://www.mysite.com/subscribe/">
    </head>
    <body>
        <h1>HTTP Status 401</h1><br>
        Unauthorized Access.  Redirecting to registration page...
    </body>
</html>

Update: I was able to get the application running without above configuration.  All I need is moving the response.setHeader code to my welcome-file specified in the web.xml file, in my case, index.jsp.
<%
  response.setHeader("WWW-Authenticate",
      "BASIC realm=\"My Realm\"");
%>
<%@ page language="java"
    contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="/home.do" />

Although I specified a logout in Spring Security configuration, it doesn't work very well.  Unless I close down all browsers opened at the same time, I'll be logged right back in by the browser's memory cache.  So I ended up adding a "You are now logged out!  Please close the main window to clean up browser cache!" message in the logout.html page.  And finally, Business decided to remove the logout link on the page.  Looks like a form-based authentication is a better choice.