O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.9. Using JAAS in a JSP

Problem

You want to use a JSP and JAAS to authenticate clients.

Solution

Create a JavaBean that wraps the functionality of the JAAS API classes that you have included in your web application.

Discussion

Recipe 15.5-Recipe 15.7 cover the JAAS basics, so this recipe focuses on adapting a JSP to the JAAS security API.

The JSP in this recipe uses a JavaBean to perform the login.

The JavaBean in Example 15-13 has two properties (in the form of instance variables): a ServletRequest and a boolean value indicating whether the name and password have passed the login test. The bean passes the ServletRequest to the WebCallbackHandler constructor; the WebCallbackHandler ultimately extracts the username and password from request parameters.

Example 15-13. A JavaBean uses the JAAS API to perform authentication

package com.jspservletcookbook;           

import javax.servlet.ServletRequest;import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

public class LoginBean {

    //private bean instance variables or properties
    private ServletRequest req;
    boolean loginSuccess;
    

  public LoginBean( ){ }//bean's no-args constructor

  public boolean getLoginSuccess( ) throws LoginException { //the ServletRequest property has to be set before this //method is called, because that's where we get the //username and password from if (req == null) throw new IllegalStateException( "The ServletRequest cannot be null in getLogin( )"); WebCallbackHandler webcallback = new WebCallbackHandler(req); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required