Prompting for AuthenticationThis code snippet describes how to prompt for HTTP Basic Authentication using a Java Servlet. The extension sends back a '401 Authenticate' response to the client if the client has not provided authentication credentials, or if the client's credentials are not valid. This response will generally cause a client's browser to display a dialog box requesting a user's credentials:
The code
public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
try {
ZXTMHttpServletRequest zreq = (ZXTMHttpServletRequest)req;
String[] userPass = zreq.getRemoteUserAndPassword();
if( userPass == null ) throw new Exception( "No Authentication details" );
// Username is userPass[0], password is userPass[1]
// Put your test here...
if( <Credentials do not match> )
throw new Exception( "Credentials do not match" );
// No exceptions thrown... must have been successful ;-)
return;
} catch( Exception e ) {
res.setHeader( "WWW-Authenticate", "Basic realm=\"Intranet - please log in\"" );
res.setHeader( "Content-Type", "text/html" );
res.setStatus( 401 );
String message =
"<html>" +
"<head><title>Unauthorized</title></head>" +
"<body>" +
"<h2>Unauthorized - please log in</h2>" +
"<p>Please log in with your system username and password</p>" +
"<p>Error: " + e.toString() + "</p>" +
"</body>" +
"</html>";
PrintWriter out = res.getWriter();
out.println( message );
}
}
You would call this Java Extension from a request rule: java.run( "CheckAuth" );
If the authentication was not successful, the call to If the authentication was successful, the Running the codeSee the Overview article, which describes how to create a Java source file from this code snippet. The Watermarking article describes how to compile and deploy an extension using an IDE like Eclipse, and the Java Develoment Guide contains a complete reference. The Active Directory article uses this code as the basis for authenticating users against an Active Directory server. It also describes how to cache authentication results in TrafficScript to improve performance and reduce the load on the authentication server.
Owen Garrett
[Zeus Dev Team] 01 July 2008
|
Recent Articles
Other Resources
|



