Sun Java logo     Previous      Contents      Index      Next     

Sun logo
Sun Java System Application Server Platform Edition 2004Q4 Beta Developer's Guide 

Chapter 2
Securing J2EE Applications

This chapter describes how to write secure J2EE applications, which contain components that perform user authentication and access authorization for servlets and EJB business logic. For information about administrative security for the server, see the Sun Java System Application Server Administration Guide.

This chapter contains the following sections:


Sun Java System Application Server Security Goals

In an enterprise computing environment, there are many security risks. The Sun Java System Application Server’s goal is to provide highly secure, interoperable, and distributed component computing based on the J2EE security model. Security goals include:


Sun Java System Application Server Specific Security Features

The Sun Java System Application Server supports the J2EE v1.4 security model, as well as the following features which are specific to the Sun Java System Application Server:


Sun Java System Application Server Security Model

Secure applications require a client to be authenticated as a valid application user and have authorization to access servlets, JSP pages, and EJB business logic. Sun Java System Application Server supports security for web, ACC, web service, and JMS clients.

Applications with secure web and EJB containers can enforce the following security processes for clients:

The following diagram shows the Sun Java System Application Server security model.

Figure shows the Sun Java System Application Server security model.

Web Application and URL Authorizations

Secure web applications can have authentication and authorization properties. The web container supports three types of authentication: basic, certificate, and form-based. When a browser requests the main application URL, the web container collects the user authentication information (for example, username and password) and passes it to the security service for authentication.

Sun Java System Application Server consults the security policies (derived from the deployment descriptors) associated with the web resource to determine the security roles used to permit resource access. The web container tests the user credentials against each role to determine if it can map the user to the role.

Invocation of Enterprise Bean Methods

Once the browser client has been authenticated and authorized by the web container and the servlet or JSP performs a method call to the EJB component, the user’s credentials (gathered during the authentication process) are propagated to the EJB container. A secure EJB container has a deployment descriptor with authorization properties, which are used to enforce access control on the bean method. The EJB container uses role information received from the EJB JAR deployment descriptors to decide whether it can map the caller to the role and allow access to the bean method.

ACC Client Invocation of Enterprise Bean Methods

For ACC clients, a secure EJB container consults its security policies (obtained from the deployment descriptors) to determine if the caller has the authority to access the bean method. This process is the same for both web and ACC clients.


Security Responsibilities Overview

A J2EE platform’s primary goal is to isolate the developer from the security mechanism details and facilitate a secure application deployment in diverse environments. This goal is addressed by providing mechanisms for the application security specification requirements declaratively and outside the application.

Application Developer

The application developer is responsible for the following:

Application Assembler

The application assembler or application component provider must identify all security dependencies embedded in a component including:

Application Deployer

The Sun Java System Application Server deploytool is used to map the views provided by the assembler to the policies and mechanisms specific to the operational environment. The security mechanisms configured by the application deployer are implemented by the containers on behalf of the components hosted in the containers.

The application deployer takes all component security views provided by the assembler and uses them to secure a particular enterprise environment in the application, including:


Common Security Terminology

The most common security processes are authentication, authorization, realm assignment, and role mapping. The following sections define this terminology.

Authentication

Authentication verifies the user. For example, the user can enter a username and password in a web browser, and if those credentials match the permanent profile stored in the active realm, the user is authenticated. The user is associated with a security identity for the remainder of the session.

Authorization

Authorization permits a user to perform the desired operations, after being authenticated. For example, a human resources application can authorize managers to view personal employee information for all employees, but allow employees to only view their own personal information.

Realms

A realm, also called a security policy domain or security domain in the J2EE specification, is a scope over which a common security policy is defined and enforced by the security administrator of the security service. Supported realms in Sun Java System Application Server are file, ldap, certificate, and solaris. For information about how to configure a realm, see Realm Configuration.

Role Mapping

A client can be defined in terms of a security role. For example, a company might use its employee database to generate both a company wide phone book application and to generate payroll information. Obviously, while all employees might have access to phone numbers and email addresses, only some employees would have access to the salary information. Employees with the right to view or change salaries might be defined as having a special security role.

A role is different from a user group in that a role defines a function in an application, while a group is a set of users who are related in some way. For example, members of the groups astronauts, scientists, and (occasionally) politicians all fit into the role of SpaceShuttlePassenger.

The EJB security model describes roles (as distinguished from user groups) as being described by an application developer and independent of any particular domain. Groups are specific to a deployment domain. It is up to the deployer to map roles into one or more groups for each application or module.

In the Sun Java System Application Server, roles correspond to users or groups (or both) configured in the active realm.


Container Security

The component containers are responsible for providing J2EE application security. There are two security forms provided by the container:

Programmatic Security

Programmatic security is when an EJB component or servlet uses method calls to the security API, as specified by the J2EE security model, to make business logic decisions based on the caller or remote user’s security role. Programmatic security should only be used when declarative security alone is insufficient to meet the application’s security model.

The J2EE specification, v1.4 defines programmatic security as consisting of two methods of the EJB EJBContext interface and two methods of the servlet HttpServletRequest interface. The Sun Java System Application Server supports these interfaces as specified in the specification.

For more information on programmatic security, see the following:

Declarative Security

Declarative security means that the security mechanism for an application is declared and handled externally to the application. Deployment descriptors describe the J2EE application’s security structure, including security roles, access control, and authentication requirements.

The Sun Java System Application Server supports the DTDs specified by J2EE v1.4 and has additional security elements included in its own deployment descriptors. Declarative security is the application deployer’s responsibility.

There are two levels of declarative security, as follows:

Application Level Security

The application XML deployment descriptor (application.xml) contains authorization descriptors for all user roles for accessing the application’s servlets and EJB components. On the application level, all roles used by any application container must be listed in a role-name element in this file. The role names are scoped to the EJB XML deployment descriptors (ejb-jar.xml and sun-ejb-jar.xml files) and to the servlet XML deployment descriptors (web.xml and sun-web.xml files). The sun-application.xml file must also contain matching security-role-mapping elements for each role-name used by the application.

Component Level Security

Component level security encompasses web components and EJB components.

A secure web container authenticates users and authorizes access to a servlet or JSP by using the security policy laid out in the servlet XML deployment descriptors (web.xml and sun-web.xml files). Once the user has been authenticated and authorized, the servlet passes on user credentials to an EJB component to establish a secure association with the bean.

The EJB container is responsible for authorizing access to a bean method by using the security policy laid out in the EJB XML deployment descriptors (ejb-jar.xml and sun-ejb-jar.xml files).


Guide to Security Information

Each information type below is shown with a short description, the location where the information resides, how to create the information, how to access the information, and where to look for further information.

User Information

User name, password, and so on.

Location:

The location of the user information depends on the realm being used:

For more information about these realms, see Realm Configuration.

How to Create:

How to create users and define groups is specific to the realm being used. The Sun Java System Application Server does not provide administration capabilities for external realms such as Solaris/PAM or LDAP. Consult your Solaris or LDAP server documentation for details.

Security Roles

Role that defines an application function, made up of a number of users, groups, or both. The relationship between users and groups is determined by the specific realm implementation being used.

Location:

Roles are defined in the J2EE application deployment descriptors.

How to Create:

Use the Sun Java System Application Server Administration Console, the deploytool, or the asadmin deploy command for application assembly and deployment.

How To Access:

Use isCallerInRole() to test for a user’s role membership. For example, in the following code, if securedMethod() can be accessed by the Manager role, the call to sctx.isCallerInRole("Manager") returns true.

public class SecTestEJB implements SessionBean
{
  private SessionContext sctx = null;

  public void setSessionContext(SessionContext sc)
  {
    sctx = sc;
  }

  public void securedMethod( )
  {
    System.out.println( sctx.isCallerInRole( "Manager" ) );
  }
}


Realm Configuration

This section covers the following topics:

How to Configure a Realm and Set the Default Realm

You can configure a realm in one of these ways:

How to Set a Realm for an Application or Module

The following deployment descriptor elements have optional realm or realm-name data subelements that override the domain’s default realm:

If modules within an application specify conflicting realms, these are ignored. If present, the realm defined in sun-application.xml is used, otherwise the domain’s default realm is used.

For example, a realm is specified in sun-application.xml as follows:

<sun-application>
  ...
  <realm>ldap</realm>
</sun-application>

For more information about the deployment descriptor files and elements, see Chapter 5, “Deployment Descriptor Files.”

Supported Realms

The following realms are supported in Sun Java System Application Server:

file

The file realm is the default realm when you first install the Sun Java System Application Server. It has the following configuration characteristics:

Required properties are as follows:

The user information file is initially empty, so you must add users before you can use the file realm. You can configure users in one of these ways:

ldap

The ldap realm allows you to use an LDAP database for user security information. It has the following configuration characteristics:

Required properties are as follows:

You can add the following optional properties to tailor the LDAP realm behavior.

You must create the user(s) in your LDAP directory. You can do this from the Sun Java™ System Directory Proxy Server 5 2004Q2 console in the Users & Groups main tab, or through any other administration tool which supports LDAP and your directory’s schema.

The principal-name used in the deployment descriptors must correspond to your LDAP user information.

For example, suppose an LDAP user, joe java, is defined in your LDAP directory as follows:

uid=jjava,ou=People,dc=acme,dc=com
uid=jjava
givenName=joe
objectClass=top
objectClass=person
objectClass=organizationalPerson
objectClass=inetorgperson
sn=java
cn=joe java

The required properties in the ldap realm configuration would be as follows:

certificate

The certificate realm supports SSL authentication. This realm sets up the user identity in the Sun Java System Application Server’s security context, and populates it with user data obtained from cryptographically verified client certificates in the cacerts.jks and keystore.jks files, which are located in domain_dir/config by default. The J2EE containers then handle authorization processing based on each user’s DN from his or her certificate. This realm has the following configuration characteristics:

You can add the following optional property to tailor the certificate realm behavior.

When you deploy an application, you must specify CLIENT-CERT as the authentication mechanism in the web.xml file as follows:

<login-config>
  <auth-method>CLIENT-CERT</auth-method>
</login-config>

You must obtain a client certificate and install it in your browser to complete the setup for client certificate authentication. For details on how to set up the server and client certificates, see the Sun Java System Application Server Administration Guide.

To configure SSL authentication using the Administration Console, open the HTTP Service or ORB component under the relevant configuration, open the HTTP Listeners or IIOP Listeners component, and select the listener for which you want to configure SSL. For details, see the Sun Java System Application Server Administration Guide.

You can change the location of the cacerts.jks and keystore.jks files as follows:

  1. Set the $TRUSTSTORE and $KEYSTORE system variables to the locations of the cacerts.jks and keystore.jks files.
  2. In the Administration Console, select the JVM Settings component under the relevant configuration (JVM™ is an abbreviation of Java™ Virtual Machine). For details, see the Sun Java System Application Server Administration Guide.
  3. Add the following to the Debug Options field:
  4. -Djavax.net.ssl.trustStore=$TRUSTSTORE -Djavax.net.ssl.keyStore=$KEYSTORE

  5. Click Save, then restart the server.

solaris

The solaris realm allows authentication using Solaris username+password data. This realm is only supported on Solaris 9. It has the following configuration characteristics:

Required properties are as follows:

Creating a Custom Realm

You can create a custom realm by providing a Java Authentication and Authorization Service (JAAS) login module and a realm implementation. Note that client-side JAAS login modules are not suitable for use with Sun Java System Application Server. For more information about JAAS, refer to the JAAS specification for Java 2 SDK, v 1.4, available here:

http://java.sun.com/products/jaas/

Custom realms must extend the com.sun.enterprise.security.auth.login.PasswordLoginModule class. This class extends javax.security.auth.spi.LoginModule. Custom realms must not extend LoginModule directly.

Custom login modules must provide an implementation for one abstract method defined in PasswordLoginModule:

abstract protected void authenticate() throws LoginException

This method performs the actual authentication. The custom login module must not implement any of the other methods, such as login(), logout(), abort(), commit(), or initialize(). Default implementations are provided in PasswordLoginModule which hook into Sun Java System Application Server infrastructure.

The custom login module can access the following protected object fields, which it inherits from PasswordLoginModule. These contain the user name and password of the user to be authenticated:

protected String _username;

protected String _password;

The authenticate() method must end with the following sequence:

String[] grpList;
// populate grpList with the set of groups to which
// _username belongs in this realm, if any
return commitAuthentication(_username, _password, _currentRealm, grpList);

Custom realms must also implement a Realm class which extends the com.sun.enterprise.security.auth.realm.IASRealm class.

Custom realms must implement the following methods:

public void init(Properties props) throws BadRealmException, NoSuchRealmException

This method is invoked during server startup when the realm is initially loaded. The props argument contains the properties defined for this realm in domain.xml. The realm can do any initialization it needs in this method. If the method returns without throwing an exception, Sun Java System Application Server assumes the realm is ready to service authentication requests. If an exception is thrown, the realm is disabled.

public String getAuthType()

This method returns a descriptive string representing the type of authentication done by this realm.

public abstract Enumeration getGroupNames(String username) throws InvalidOperationException, NoSuchUserException

This method returns an Enumeration (of String objects) enumerating the groups (if any) to which the given username belongs in this realm.


JACC Support

JACC (Java Authorization Contract for Containers) is part of the J2EE 1.4 specification and defined by JSR-115. JACC defines an interface for pluggable authorization providers. This provides third parties with a mechanism to develop and plug in modules that are responsible for answering authorization decisions during J2EE application execution. The interfaces and rules used for developing JACC providers are defined in the JACC 1.0 specification.

The Sun Java System Application Server provides a simple file-based JACC-compliant authorization engine as a default JACC provider. To configure an alternate provider using the Administration Console, open the Security component under the relevant configuration, and select the JACC Providers component. For details, see the Sun Java System Application Server Administration Guide.


Pluggable Audit Module Support

You can create a custom audit module. This section covers the following topics:

Configuring an Audit Module

To configure an audit module, you can perform one of the following tasks:

The AuditModule Class

You can create a custom audit module by implementing a class that extends com.sun.appserv.security.AuditModule. The AuditModule class provides default “no-op” implementations for each of the following methods, which your custom class can override.

public void init(Properties props)

This method is invoked during server startup when the audit module is initially loaded. The props argument contains the properties defined for this module in domain.xml. The module can do any initialization it needs in this method. If the method returns without throwing an exception, Sun Java System Application Server assumes the module realm is ready to service audit requests. If an exception is thrown the module is disabled.

public void authentication(String user, String realm, boolean success)

This method is invoked when an authentication request has been processed by a realm for the given user. The success flag indicates whether the authorization was granted or denied.

public void webInvocation(String user, HttpServletRequest req, String type, boolean success)

This method is invoked when a web container call has been processed by authorization. The success flag indicates whether the authorization was granted or denied. The req object is the standard HttpServletRequest object for this request. The type string is one of hasUserDataPermission or hasResourcePermission (see JSR-115).

public void ejbInvocation(String user, String ejb, String method, boolean success)

This method is invoked when an EJB container call has been processed by authorization. The success flag indicates whether the authorization was granted or denied. The ejb and method strings describe the EJB component and its method that is being invoked.

public void shutdown()

This method is invoked once, during normal server shutdown. It provides the audit module an opportunity to record server shutdown events and to perform any necessary internal cleanup.


The server.policy File

Each Sun Java System Application Server domain has its own standard J2SE policy file, located in the domain root directory, typically install_dir/domains/domain_dir/config. The file is named server.policy.

Sun Java System Application Server is a J2EE 1.4-compliant application server. As such, it follows the requirements of the J2EE specification, including the presence of the security manager (the Java component that enforces the policy) and a limited permission set for J2EE application code.

This section covers the following topics:

Default Permissions

Internal server code is granted all permissions. These are covered by the AllPermission grant blocks to various parts of the server infrastructure code. Do not modify these entries.

Application permissions are granted in the default grant block. These permissions apply to all code not part of the internal server code listed previously. Sun Java System Application Server does not distinguish between EJB and web module permissions. All code is granted the minimal set of Web component permissions (which is a superset of the EJB minimal set).

A few permissions above the minimal set are also granted in the default server.policy file. These are necessary due to various internal dependencies of the server implementation. J2EE application developers must not rely on these additional permissions.

One additional permission is granted specifically for using connectors. If connectors are not used in a particular domain, you should remove this permission, because it is not otherwise necessary.

Changing Permissions for an Application

The default policy for each domain limits the permissions of J2EE deployed applications to the minimal set of permissions required for these applications to operate correctly. If you develop applications that require more than this default set of permissions, you can edit the server.policy file to add the custom permissions that your applications need.

You should add the extra permissions only to the applications that require them, not to all applications deployed to a domain. Do not add extra permissions to the default set (the grant block with no codebase, which applies to all code). Instead, add a new grant block with a codebase specific to the application requiring the extra permissions, and only add the minimally necessary permissions in that block.


Note

Do not add java.security.AllPermission to the server.policy file for application code. Doing so completely defeats the purpose of the security manager, yet you still get the performance overhead associated with it.


As noted in the J2EE specification, an application should provide documentation of the additional permissions it needs. If an application requires extra permissions but does not document the set it needs, contact the application author for details.

As a last resort, you can iteratively determine the permission set an application needs by observing AccessControlException occurrences in the server log. If this is not sufficient, you can add the -Djava.security.debug=all JVM option to the domain. For details, see the Sun Java System Application Server Administration Guide or the Sun Java System Application Server Reference.

You can use the J2SE standard policytool or any text editor to edit the server.policy file. For more information, see:

http://java.sun.com/docs/books/tutorial/security1.2/tour2/index.html

For detailed information about the permissions you can set in the server.policy file, see:

http://java.sun.com/j2se/1.4/docs/guide/security/permissions.html

The Javadoc for the Permission class is here:

http://java.sun.com/j2se/1.4/docs/api/java/security/Permission.html


Programmatic Login

Programmatic login allows a deployed J2EE application to invoke a login method. If the login is successful, a SecurityContext is established as if the client had authenticated using any of the conventional J2EE mechanisms.

Programmatic login is useful for an application that has special needs which cannot be accommodated by any of the J2EE standard authentication mechanisms.


Note

Programmatic login is specific to Sun Java System Application Server and not portable to other application servers.


This section contains the following topics:

Precautions

The Sun Java System Application Server is not involved in how the login information (user, password) is obtained by the deployed application. Programmatic login places the burden on the application developer with respect to assuring that the resulting system meets their security requirements. If the application code reads the authentication information across the network, it is up to the application to determine whether to trust the user.

Programmatic login allows the application developer to bypass the application server-supported authentication mechanisms and feed authentication data directly to the security service. While flexible, this capability should not be used without some understanding of security issues.

Since this mechanism bypasses the container-managed authentication process and sequence, the application developer must be very careful in making sure that authentication is established before accessing any restricted resources or methods. It is also the application developer’s responsibility to verify the status of the login attempt and to alter the behavior of the application accordingly.

The programmatic login state does not necessarily persist in sessions or participate in single sign-on.

Lazy authentication is not supported for programmatic login. If an access check is reached and the deployed application has not properly authenticated via the programmatic login method, access is denied immediately and the application might fail if not properly coded to account for this occurrence.

Granting Programmatic Login Permission

The ProgrammaticLoginPermission permission is required to invoke the programmatic login mechanism for an application. This permission is not granted by default to deployed applications because this is not a standard J2EE mechanism.

To grant the required permission to the application, add the following to the domain_dir/config/server.policy file:

grant codeBase "file:jar_file_path" {
  permission com.sun.appserv.security.ProgrammaticLoginPermission
  "login";
};

The jar_file_path is the path to the application’s JAR file.

For more information about the server.policy file, see The server.policy File.

The ProgrammaticLogin Class

The com.sun.appserv.security.ProgrammaticLogin class enables a user to perform login programmatically. This class has four login methods, two for servlets or JSP pages and two for EJB components.

The login methods for servlets or JSP pages have the following signatures:

public Boolean login(String user, String password, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

public Boolean login(String user, String password, String realm, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, boolean errors) throws Exception

The login methods for EJB components have the following signatures:

public Boolean login(String user, String password)

public Boolean login(String user, String password, String realm, boolean errors) throws Exception

All of theselogin methods:

The methods with errors flags propagate to the caller any exceptions encountered during the authentication and return true upon a successful authentication. The login occurs on the realm specified unless it is null, in which case the domain’s default realm is used. The methods with no realm parameter use the domain’s default realm.

The logout method for servlets or JSP pages has the following signature:

public Boolean login(String user, String password, String realm, HttpServletRequest request, HttpServletResponse response, boolean errors) throws Exception

The logout method for EJB components has the following signature:

public Boolean login(String user, String password, String realm, boolean errors) throws Exception

The errors flags are used to propagate to the caller any exceptions encountered during the logout. These methods return true upon a successful logout. The logout occurs on the realm specified unless it is null, in which case the domain’s default realm is used.


User Authentication for Single Sign-on

The single sign-on across applications on the Sun Java System Application Server is supported by the Sun Java System Application Server servlets and JSP pages. This feature allows multiple applications that require the same user sign-on information to share this information between them, rather than having the user sign-on separately for each application. These applications are created to authenticate the user one time, and when needed this authentication information is propagated to all other involved applications.

An example application using the single sign-on scenario could be a consolidated airline booking service that searches all airlines and provides links to different airline web sites. Once the user signs on to the consolidated booking service, the user information can be used by each individual airline site without requiring another sign-on.

Single sign-on operates according to the following rules:

The single sign-on feature utilizes HTTP cookies to transmit a token that associates each request with the saved user identity, so it can only be used in client environments that support cookies.

To configure single sign-on, set the following properties in the virtual-server element of the domain.xml file:

Here is an example configuration with all default values:

<virtual-server id="server1" ... >
  ...
  <property name="sso-enabled" value="true"/>
  <property name="sso-max-inactive-seconds" value="300"/>
  <property name="sso-reap-interval-seconds" value="60"/>
</virtual-server>


Defining Roles

You define roles in the J2EE deployment descriptor file, web.xml, and the corresponding role mappings in the Sun Java System Application Server deployment descriptor file, sun-application.xml (or sun-web.xml for individually deployed web modules).

For more information regarding web.xml elements, see Chapter 13, “Deployment Descriptor,” of the Java Servlet Specification, v2.3. For more information regarding sun-web.xml and sun-application.xml elements, see Chapter 5, “Deployment Descriptor Files.”

Each security-role-mapping element in the sun-application.xml or sun-web.xml file maps a role name permitted by the web application to principals and groups. For example, a sun-web.xml file for an individually deployed web module might contain the following:

<sun-web-app>
  <security-role-mapping>
    <role-name>manager</role-name>
    <principal-name>jgarcia</principal-name>
    <principal-name>mwebster</principal-name>
    <group-name>team-leads</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>administrator</role-name>
    <principal-name>dsmith</principal-name>
  </security-role-mapping>
</sun-web-app>

Note that the role-name in this example must match the role-name in the security-role element of the corresponding web.xml file.

Note that for J2EE applications (EAR files), all security role mappings for the application modules must be specified in the sun-application.xml file. For individually deployed web modules, the roles are always specified in the sun-web.xml file. A role can be mapped to either specific principals or to groups (or both). The principal or group names used must be valid principals or groups in the current default realm.


Authenticating an Application Client Using the JAAS Module

Using the JAAS module, you can provide security in your application client code by creating a LoginModule that describes the interface implemented by authentication technology providers. For general information about application clients, see Chapter 9, "Developing Java Clients."

The following steps are involved in creating a LoginModule:

  1. Write the LoginModule interface.
  2. public class ClientPasswordLoginModule implements LoginModule{
      private static Logger _logger=null;
        static{
        _logger=LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
        }
      }
      private Subject subject;
      private CallbackHandler callbackHandler;
      private Map sharedState;
      private Map options;
      ...
    }

    The standard JAAS package required by this class is javax.security. The code line below illustrates how you can import the package in your client application:

    import javax.security.*;

  3. Initialize the LoginModule interface that you just created.
  4. public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
      this.subject = subject;
      this.callbackHandler = callbackHandler;
      this.sharedState = sharedState;
      this.options = options;
    }

    • The parameter subject, is the subject to be authenticated.
    • callbackHandler, for communicating with the end user which prompts for the username and password.
    • sharedState, is the shared LoginModule state.
    • options, the options specified in the configuration file of the LoginModule.
  5. Use login() method to fetch the login information from the client application and authenticate the user.
  6. public boolean login() throws LoginException {
      if (uname != null) {
        username = new String (uname);
        pswd = System.getProperty (LOGIN_PASSWORD);
      ...
    }

    The login information is fetched using the CallBackHandler.

    Callback[] callbacks = new Callback[2];

    callbacks[0] = new NameCallback(localStrings.getLocalString("login.username", "ClientPasswordModule username: "));

    callbacks[1] = new PasswordCallback(localStrings.getLocalString("login.password", "ClientPasswordModule password: "), false);

    username = ((NameCallback)callbacks[0]).getName();

    char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();

    The login() method tries to connect to the server using the login information that is fetched. If the connection is established, the method returns the value true.

  7. Use commit() method to set the subject in the session to the user name that is verified by the login method. If the commit method returns a value true, then this method associates PrincipalImpl with the subject located in the LoginModule. If this LoginModule’s own authentication attempt is failed, then this method removes any state that was originally saved.
  8. public boolean commit() throws LoginException {
      if (succeeded == false) {
        return false;
        } else {
        // add a Principal (authenticated identity)to the Subject
        // assume the user we authenticated is the PrincipalImpl
        userPrincipal = new PrincipalImpl(username);
      ...
    }

  9. Use logout() method to remove the privilege settings associated with the roles of the subject.
  10. public boolean logout() throws LoginException {
      subject.getPrincipals().remove(userPrincipal);
      succeeded = false;
      succeeded = commitSucceeded;
      username = null;
      if (password != null) {
        for (int i = 0; i < password.length; i++)
          password[i] = ’ ’;
          password = null;
      }
      userPrincipal = null;
      return true;
    }

  11. Edit the sun-acc.xml deployment descriptor to configure JAAS authentication for the client.
  12. Integrate the LoginModule with the application server. Edit the deployment descriptor to make the following changes:
    • Configure the server with a realm that uses a specific LoginModule for security authentication.
    • Map the application realm and roles to the realm and roles defined by the LoginModule.
  13. Assemble the application client.
Sample Code

The sample code of ClinetLoginPasswordModule is given below:

package com.sun.enterprise.security.auth.login;

import java.util.*;
import java.io.IOException;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import com.sun.enterprise.security.auth.login.PasswordCredential;
import com.sun.enterprise.security.PrincipalImpl;
import com.sun.enterprise.security.auth.LoginContextDriver;
import com.sun.enterprise.util.LocalStringManagerImpl;
import java.util.logging.*;
import com.sun.logging.*;

public class ClientPasswordLoginModule implements LoginModule {

  private static Logger _logger=null;
    static{
      _logger=LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
    }

  private static final String DEFAULT_REALMNAME = "default";
  private static LocalStringManagerImpl localStrings =
    new LocalStringManagerImpl(ClientPasswordLoginModule.class);

// initial state

  private Subject subject;
  private CallbackHandler callbackHandler;
  private Map sharedState;
  private Map options;

  private boolean debug =
    com.sun.enterprise.util.logging.Debug.enabled;

// the authentication status

  private boolean succeeded = false;
  private boolean commitSucceeded = false;

// username and password

  private String username;
  private char[] password;

  private final PasswordCredential passwordCredential=null;

// testUser’s PrincipalImpl

  private PrincipalImpl userPrincipal;
  public static String LOGIN_NAME = "j2eelogin.name";
  public static String LOGIN_PASSWORD = "j2eelogin.password";

  public void initialize(Subject subject, CallbackHandler
    callbackHandler, Map sharedState, Map options) {

    this.subject = subject;
    this.callbackHandler = callbackHandler;
    this.sharedState = sharedState;
    this.options = options;

// initialize any configured options

    debug =
    "true".equalsIgnoreCase((String)options.get("debug"));

  }

/* Authenticate the user by prompting for a username and password. @return true in all cases since this <code>LoginModule</code> should not be ignored.*/

/* @exception FailedLoginException if the authentication fails. @exception LoginException if this <code>LoginModule</code> is unable to perform the authentication.*/

  public boolean login() throws LoginException {

  // prompt for a username and password

    if (callbackHandler == null){

      String failure =
        localStrings.getLocalString("login.nocallback","Error:
        no CallbackHandler available to garner authentication
        information from the user");

      throw new LoginException(failure);
    }

    String uname = System.getProperty (LOGIN_NAME);
    String pswd;

    if (uname != null) {

      username = new String (uname);
      pswd = System.getProperty (LOGIN_PASSWORD);
      char[] dest;
      if (pswd == null){
        dest = new char[0];
        password = new char[0];
      } else {
        int length = pswd.length();
        dest = new char[length];
        pswd.getChars(0, length, dest, 0 );
        password = new char[length];
      }
      System.arraycopy (dest, 0, password, 0, dest.length);
    } else {
      Callback[] callbacks = new Callback[2];
      callbacks[0] = new
    NameCallback(localStrings.getLocalString("login.username",
    "ClientPasswordModule username: "));
      callbacks[1] = new
  PasswordCallback(localStrings.getLocalString("login.password",
  "ClientPasswordModule password: "), false);
    }

    try {
      callbackHandler.handle(callbacks);
      username = ((NameCallback)callbacks[0]).getName();
      if(username == null){
        String fail =
          localStrings.getLocalString("login.nousername",
          "No user specified");
        throw new LoginException(fail);
      }

      char[] tmpPassword =
        ((PasswordCallback)callbacks[1]).getPassword();

      if (tmpPassword == null) {
      // treat a NULL password as an empty password
        tmpPassword = new char[0];
      }
      password = new char[tmpPassword.length];
      System.arraycopy(tmpPassword, 0,
        password, 0, tmpPassword.length);
        ((PasswordCallback)callbacks[1]).clearPassword();
    } catch (java.io.IOException ioe) {
      throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
      String nocallback =
        localStrings.getLocalString("login.callback","Error:
        Callback not available to garner authentication
        information from user(CallbackName):" );

      throw new LoginException(nocallback +
        uce.getCallback().toString());

    }

// print debugging information
    if (debug) {

      for (int i = 0; i < password.length; i++){
        //System.out.print(password[i]);
      }
      //System.out.println();
    }

// by default - the client side login module always says
// that the login successful. The actual login takes place
// on the server side.
    if (debug) {
      _logger.log(Level.FINE,"    [ClientPasswordLoginModule] "
        +"authentication succeeded");
      succeeded = true;
      return true;
    }

  }

  public boolean commit() throws LoginException {
    if (succeeded == false) {
      return false;
    } else {
    // add a Principal (authenticated identity)to the Subject
    // assume the user we authenticated is the PrincipalImpl
      userPrincipal = new PrincipalImpl(username);
      if (!subject.getPrincipals().contains(userPrincipal))
        subject.getPrincipals().add(userPrincipal);
      if (debug) {
        _logger.log(Level.FINE,"[ClientPasswordLoginModule] "
        + "added PrincipalImpl to Subject");
      }

      PasswordCredential pc = new PasswordCredential(username,
        new String(password), realm);
if(!subject.getPrivateCredentials().contains(pc))subject.getPrivateCredent ials().add(pc);

      username = null;
      for (int i = 0; i < password.length; i++){
        password[i] = ’ ’;
        password = null;
        commitSucceeded = true;
        return true;
      }
    }
  }

  public boolean abort() throws LoginException {
    if (succeeded == false) {
      return false;
    } else if (succeeded == true && commitSucceeded == false) {
  // login succeeded but overall authentication failed
      succeeded = false;
      username = null;
      if (password != null) {
        for (int i = 0; i < password.length; i++)
          password[i] = ’ ’;
          password = en das ull;
      }

    userPrincipal = null;
    } else {

    // overall authentication succeeded and commit succeeded,
    // but someone else’s commit failed
    logout();
    }
    return true;
  }

  public boolean logout() throws LoginException {
    subject.getPrincipals().remove(userPrincipal);
    succeeded = false;
    succeeded = commitSucceeded;
    username = null;
    if (password != null) {
      for (int i = 0; i < password.length; i++)
        password[i] = ’ ’;
        password = null;
    }
    userPrincipal = null;
    return true;
  }

}



Previous      Contents      Index      Next     


Part No: 819-0079.   Copyright 2004 Sun Microsystems, Inc. All rights reserved.