Sun Java System Application Server 9.1 Developer's Guide

Chapter 5 Securing Applications

This chapter describes how to write secure Java EE applications, which contain components that perform user authentication and access authorization for the business logic of Java EE components.

For information about administrative security for the Application Server, see Chapter 9, Configuring Security, in Sun Java System Application Server 9.1 Administration Guide.

For general information about Java EE security, see “Chapter 29: Introduction to Security in Java EE” in the Java EE 5 Tutorial.

This chapter contains the following sections:

Security Goals

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

Application Server Specific Security Features

The Application Server supports the Java EE security model, as well as the following features which are specific to the Application Server:

Container Security

The component containers are responsible for providing Java EE application security. The container provides two security forms:

Annotations (also called metadata) enable a declarative style of programming, and so encompass both the declarative and programmatic security concepts. Users can specify information about security within a class file using annotations. When the application is deployed, this information can either be used by or overridden by the application or module deployment descriptor.

Declarative Security

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

The Application Server supports the deployment descriptors specified by Java EE and has additional security elements included in its own deployment descriptors. Declarative security is the application deployer’s responsibility. For more information about Sun-specific deployment descriptors, see the Sun Java System Application Server 9.1 Application Deployment Guide.

There are two levels of declarative security, as follows:

Application Level Security

For an application, roles used by any application container must be defined in @DeclareRoles annotations in the code or role-name elements in the application deployment descriptor (application.xml). 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). For an individually deployed web or EJB module, you define roles using @DeclareRoles annotations or role-name elements in the Java EE deployment descriptor files web.xml or ejb-jar.xml.

To map roles to principals and groups, define matching security-role-mapping elements in the sun-application.xml, sun-ejb-jar.xml, or sun-web.xml file for each role-name used by the application. For more information, see Roles, Principals, and Principal to Role Mapping.

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).

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).

Programmatic Security

Programmatic security involves an EJB component or servlet using method calls to the security API, as specified by the Java EE 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 Java EE specification defines programmatic security as consisting of two methods of the EJB EJBContext interface and two methods of the servlet HttpServletRequest interface. The Application Server supports these interfaces as specified in the specification.

For more information on programmatic security, see the following:

Roles, Principals, and Principal to Role Mapping

For applications, you define roles in @DeclareRoles annotations or the Java EE deployment descriptor file application.xml. You define the corresponding role mappings in the Application Server deployment descriptor file sun-application.xml. For individually deployed web or EJB modules, you define roles in @DeclareRoles annotations or the Java EE deployment descriptor files web.xml or ejb-jar.xml. You define the corresponding role mappings in the Application Server deployment descriptor files sun-web.xml or sun-ejb-jar.xml.

For more information regarding Java EE deployment descriptors, see the Java EE Specification. For more information regarding Application Server deployment descriptors, see Appendix A, Deployment Descriptor Files, in Sun Java System Application Server 9.1 Application Deployment Guide.

Each security-role-mapping element in the sun-application.xml, sun-web.xml, or sun-ejb-jar.xml file maps a role name permitted by the application or module 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>

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 realm for the application or module. Note that the role-name in this example must match the @DeclareRoles annotations or the role-name in the security-role element of the corresponding web.xml file.

You can also specify a custom principal implementation class. This provides more flexibility in how principals can be assigned to roles. A user's JAAS login module now can authenticate its custom principal, and the authenticated custom principal can further participate in the Application Server authorization process. For example:

<security-role-mapping>
    <role-name>administrator</role-name>
    <principal-name class-name="CustomPrincipalImplClass">
        dsmith
    </principal-name>
</security-role-mapping>

You can specify a default principal and a default principal to role mapping, each of which applies to the entire Application Server instance. The default principal to role mapping maps group principals to named roles. Web modules that omit the run-as element in web.xml use the default principal. Applications and modules that omit the security-role-mapping element use the default principal to role mapping. These defaults are part of the Security Service, which you can access in the following ways:

Realm Configuration

This section covers the following topics:

Supported Realms

The following realms are supported in the Application Server:

For detailed information about configuring each of these realms, see How to Configure a Realm.

How to Configure a 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 or attributes that override the domain’s default realm:

If modules within an application specify 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 Appendix A, Deployment Descriptor Files, in Sun Java System Application Server 9.1 Application Deployment Guide.

Creating a Custom Realm

You can create a custom realm by providing a custom Java Authentication and Authorization Service (JAAS) login module class and a custom realm class. Note that client-side JAAS login modules are not suitable for use with the Application Server.

JAAS is a set of APIs that enable services to authenticate and enforce access controls upon users. JAAS provides a pluggable and extensible framework for programmatic user authentication and authorization. JAAS is a core API and an underlying technology for Java EE security mechanisms. For more information about JAAS, refer to the JAAS specification for Java SDK, available at http://java.sun.com/products/jaas/.

For general information about realms and login modules, see “Chapter 29: Introduction to Security in Java EE” in the Java EE 5 Tutorial.

For Javadoc tool pages relevant to custom realms, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

Custom login modules must extend the com.sun.appserv.security.AppservPasswordLoginModule class. This class implements javax.security.auth.spi.LoginModule. Custom login modules must not implement LoginModule directly.

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

abstract protected void authenticateUser() 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 AppservPasswordLoginModule which hook into the Application Server infrastructure.

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

protected String _username;
protected String _password;

The authenticateUser() 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 commitUserAuthentication(_username, _password, 
  _currentRealm, grpList);

Custom realms must extend the com.sun.appserv.security.AppservRealm class and 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, the Application Server assumes that 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 Java EE specification and defined by JSR 115. JACC defines an interface for pluggable authorization providers. Specifically, JACC is used to plug in the Java policy provider used by the container to perform Java EE caller access decisions. The Java policy provider performs Java policy decisions during application execution. This provides third parties with a mechanism to develop and plug in modules that are responsible for answering authorization decisions during Java EE application execution. The interfaces and rules used for developing JACC providers are defined in the JACC 1.0 specification.

The Application Server provides a simple file-based JACC-compliant authorization engine as a default JACC provider. To configure an alternate provider using the Admin Console, open the Security component under the relevant configuration, and select the JACC Providers component. For details, click the Help button in the Admin Console.

Pluggable Audit Module Support

Audit modules collect and store information on incoming requests (servlets, EJB components) and outgoing responses. You can create a custom audit module. This section covers the following topics:

For additional information about audit modules, see Audit Callbacks.

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.

For Javadoc tool pages relevant to audit modules, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

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)

The preceding 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, the 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 webServiceInvocation(String uri, String endpoint, boolean success)

This method is invoked during validation of a web service request in which the endpoint is a servlet. The uri is the URL representation of the web service endpoint. The endpoint is the name of the endpoint representation. The success flag indicates whether the authorization was granted or denied.

public void ejbAsWebServiceInvocation(String endpoint, boolean success)

This method is invoked during validation of a web service request in which the endpoint is a stateless session bean. The endpoint is the name of the endpoint representation. The success flag indicates whether the authorization was granted or denied.

The server.policy File

Each Application Server domain has its own global J2SE policy file, located in domain-dir/config. The file is named server.policy.

The Application Server is a Java EE compliant application server. As such, it follows the requirements of the Java EE specification, including the presence of the security manager (the Java component that enforces the policy) and a limited permission set for Java EE 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. The 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). Do not modify these entries.

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. Java EE application developers must not rely on these additional permissions. In some cases, deleting these permissions might be appropriate. For example, 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 Java EE deployed applications to the minimal set of permissions required for these applications to operate correctly. 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 applications requiring the extra permissions, and only add the minimally necessary permissions in that block.

If you develop multiple applications that require more than this default set of permissions, you can add the custom permissions that your applications need. The com.sun.aas.instanceRoot variable refers to the domain-dir. For example:

grant "file:${com.sun.aas.instanceRoot}/applications/j2ee-apps/-" {
...
}

You can add permissions to stub code with the following grant block:

grant "file:${com.sun.aas.instanceRoot}/generated/-" {
...
}

In general, you should add extra permissions only to the applications or modules that require them, not to all applications deployed to a domain. For example:

grant "file:${com.sun.aas.instanceRoot}/applications/j2ee-apps/MyApp/-" {
...
}

For a module:

grant "file:${com.sun.aas.instanceRoot}/applications/j2ee-modules/MyModule/-" {
...
}

An alternative way to add permissions to a specific application or module is to edit the granted.policy file for that application or module. The granted.policy file is located in the domain-dir/generated/policy/app-or-module-name directory. In this case, you add permissions to the default grant block. Do not delete permissions from this file.

When the application server policy subsystem determines that a permission should not be granted, it logs a server.policy message specifying the permission that was not granted and the protection domains, with indicated code source and principals that failed the protection check.


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 Java EE 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=failure JVM option to the domain. Use the following asadmin create-jvm-options command, then restart the server:


asadmin create-jvm-options --user adminuser -Djava.security.debug=failure

For more information about the asadmin create-jvm-options command, see the Sun Java System Application Server 9.1 Administration 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 policy file syntax, see http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html#FileSyntax.

For information about using system properties in the server.policy file, see http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html#PropertyExp. For information about Application Server system properties, see system-property in Sun Java System Application Server 9.1 Administration Reference.

For detailed information about the permissions you can set in the server.policy file, see http://java.sun.com/j2se/1.5.0/docs/guide/security/permissions.html.

The Javadoc for the Permission class is at http://java.sun.com/j2se/1.5.0/docs/api/java/security/Permission.html.

Enabling and Disabling the Security Manager

The security manager is disabled in the developer profile and enabled in the cluster profile by default.

In a production environment, you may be able to safely disable the security manager if all of the following are true:

Disabling the security manager may improve performance significantly for some types of applications. To disable the security manager, do one of the following:

Configuring Message Security for Web Services

In message security, security information is applied at the message layer and travels along with the web services message. Web Services Security (WSS) is the use of XML Encryption and XML Digital Signatures to secure messages. WSS profiles the use of various security tokens including X.509 certificates, Security Assertion Markup Language (SAML) assertions, and username/password tokens to achieve this.

Message layer security differs from transport layer security in that it can be used to decouple message protection from message transport so that messages remain protected after transmission, regardless of how many hops they travel.


Note –

In this release of the Application Server, message layer annotations are not supported.


For more information about message security, see the following:

The following web services security topics are discussed in this section:

Message Security Providers

When you first install the Application Server, the providers XWS_ClientProvider and XWS_ServerProvider are configured but disabled. You can enable them in one of the following ways:

The example described in Understanding and Running the Sample Application uses the ClientProvider and ServerProvider providers, which are enabled when the asant targets are run. You don’t need to enable these on the Application Server prior to running the example.

If you install the Access Manager, you have these additional provider choices:

Liberty specifications can be viewed at http://www.projectliberty.org/resources/specifications.php. The WS-I BSP specification can be viewed at http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html.

For more information about the Sun-specific deployment descriptor files, see the Sun Java System Application Server 9.1 Application Deployment Guide.

For information about configuring these providers in the Application Server, see Chapter 10, Configuring Message Security, in Sun Java System Application Server 9.1 Administration Guide. For additional information about overriding provider settings, see Application-Specific Message Protection.

You can create new message security providers in one of the following ways:

In addition, you can set a few optional provider properties. For more information, see the property descriptions under provider-config in Sun Java System Application Server 9.1 Administration Reference.

Message Security Responsibilities

In the Application Server, the system administrator and application deployer roles are expected to take primary responsibility for configuring message security. In some situations, the application developer may also contribute, although in the typical case either of the other roles may secure an existing application without changing its implementation and without involving the developer. The responsibilities of the various roles are defined in the following sections:

Application Developer

The application developer can turn on message security, but is not responsible for doing so. Message security can be set up by the system administrator so that all web services are secured, or set up by the application deployer when the provider or protection policy bound to the application must be different from that bound to the container.

The application developer is responsible for the following:

Application Deployer

The application deployer is responsible for the following:

These security tasks are discussed in Application-Specific Message Protection. A sample application using message security is discussed in Understanding and Running the Sample Application.

System Administrator

The system administrator is responsible for the following:

A system administrator uses the Admin Console to manage server security settings and uses a command line tool to manage certificate databases. Certificates and private keys are stored in key stores and are managed with keytool. If Network Security Services (NSS) is installed and you have selected the enterprise profile, certificates and private keys are stored in an NSS database, where they are managed using certutil. For information about profiles, see Usage Profiles in Sun Java System Application Server 9.1 Administration Guide. System administrator tasks are discussed in Chapter 10, Configuring Message Security, in Sun Java System Application Server 9.1 Administration Guide.

Application-Specific Message Protection

When the Application Server provided configuration is insufficient for your security needs, and you want to override the default protection, you can apply application-specific message security to a web service.

Application-specific security is implemented by adding the message security binding to the web service endpoint, whether it is an EJB or servlet web service endpoint. Modify Sun-specific XML files to add the message binding information.

Message security can also be specified using a WSIT security policy in the WSDL file. For details, see the WSIT page at https://wsit.dev.java.net/.

For more information about message security providers, see Message Security Providers.

For more details on message security binding for EJB web services, servlet web services, and clients, see the XML file descriptions in Appendix A, Deployment Descriptor Files, in Sun Java System Application Server 9.1 Application Deployment Guide.

This section contains the following topics:

Using a Signature to Enable Message Protection for All Methods

To enable message protection for all methods using digital signature, update the message-security-binding element for the EJB web service endpoint in the application’s sun-ejb-jar.xml file. In this file, add request-protection and response-protection elements, which are analogous to the request-policy and response-policy elements discussed in Chapter 10, Configuring Message Security, in Sun Java System Application Server 9.1 Administration Guide. To apply the same protection mechanisms for all methods, leave the method-name element blank. Configuring Message Protection for a Specific Method Based on Digital Signatures discusses listing specific methods or using wildcard characters.

This section uses the sample application discussed in Understanding and Running the Sample Application to apply application-level message security to show only the differences necessary for protecting web services using various mechanisms.

ProcedureTo Enable Message Protection for All Methods Using Digital Signature

  1. In a text editor, open the application’s sun-ejb-jar.xml file.

    For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf, where app-dir is defined in To Set Up the Sample Application.

  2. Modify the sun-ejb-jar.xml file by adding the message-security-binding element as shown:

    <sun-ejb-jar>
      <enterprise-beans>
        <unique-id>1</unique-id>
        <ejb>
          <ejb-name>HelloWorld</ejb-name>
          <jndi-name>HelloWorld</jndi-name>
          <webservice-endpoint>
            <port-component-name>HelloIF</port-component-name>
            <endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
            <message-security-binding auth-layer="SOAP">
              <message-security>
                <request-protection auth-source="content" />
                <response-protection auth-source="content"/>
              </message-security>
            </message-security-binding>
          </webservice-endpoint>
        </ejb>
      </enterprise-beans>
    </sun-ejb-jar>
  3. Compile, deploy, and run the application as described in To Run the Sample Application.

Configuring Message Protection for a Specific Method Based on Digital Signatures

To enable message protection for a specific method, or for a set of methods that can be identified using a wildcard value, follow these steps. As in the example discussed in Using a Signature to Enable Message Protection for All Methods, to enable message protection for a specific method, update the message-security-binding element for the EJB web service endpoint in the application’s sun-ejb-jar.xml file. To this file, add request-protection and response-protection elements, which are analogous to the request-policy and response-policy elements discussed in Chapter 10, Configuring Message Security, in Sun Java System Application Server 9.1 Administration Guide. The administration guide includes a table listing the set and order of security operations for different request and response policy configurations.

This section uses the sample application discussed in Understanding and Running the Sample Application to apply application-level message security to show only the differences necessary for protecting web services using various mechanisms.

ProcedureTo Enable Message Protection for a Particular Method or Set of Methods Using Digital Signature

  1. In a text editor, open the application’s sun-ejb-jar.xml file.

    For the xms example, this file is located in the directory app-dir/xms-ejb/src/conf, where app-dir is defined in To Set Up the Sample Application.

  2. Modify the sun-ejb-jar.xml file by adding the message-security-binding element as shown:

    <sun-ejb-jar>
      <enterprise-beans>
      <unique-id>1</unique-id>
        <ejb>
          <ejb-name>HelloWorld</ejb-name>
          <jndi-name>HelloWorld</jndi-name>
          <webservice-endpoint>
            <port-component-name>HelloIF</port-component-name>
            <endpoint-address-uri>service/HelloWorld</endpoint-address-uri>
            <message-security-binding auth-layer="SOAP">
              <message-security>
                <message>
                  <java-method>
                    <method-name>ejbCreate</method-name>
                  </java-method>
                </message>
                <message>
                  <java-method>
                    <method-name>sayHello</method-name>
                  </java-method>
                </message>
                <request-protection auth-source="content" />
                <response-protection auth-source="content"/>
              </message-security>
            </message-security-binding>
          </webservice-endpoint>
        </ejb>
      </enterprise-beans>
    </sun-ejb-jar>
  3. Compile, deploy, and run the application as described in To Run the Sample Application.

Understanding and Running the Sample Application

This section discusses the WSS sample application. This sample application is installed on your system only if you installed the J2EE 1.4 samples. If you have not installed these samples, see To Set Up the Sample Application.

The objective of this sample application is to demonstrate how a web service can be secured with WSS. The web service in the xms example is a simple web service implemented using a Java EE EJB endpoint and a web service endpoint implemented using a servlet. In this example, a service endpoint interface is defined with one operation, sayHello, which takes a string then sends a response with Hello prefixed to the given string. You can view the WSDL file for the service endpoint interface at app-dir/xms-ejb/src/conf/HelloWorld.wsdl, where app-dir is defined in To Set Up the Sample Application.

In this application, the client looks up the service using the JNDI name java:comp/env/service/HelloWorld and gets the port information using a static stub to invoke the operation using a given name. For the name Duke, the client gets the response Hello Duke!

This example shows how to use message security for web services at the Application Server level. For information about using message security at the application level, see Application-Specific Message Protection. The WSS message security mechanisms implement message-level authentication (for example, XML digital signature and encryption) of SOAP web services invocations using the X.509 and username/password profiles of the OASIS WS-Security standard, which can be viewed from the following URL: http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf.

This section includes the following topics:

ProcedureTo Set Up the Sample Application

Before You Begin

To have access to this sample application, you must have previously installed the J2EE 1.4 samples. If the samples are not installed, follow the steps in the following section.

After you follow these steps, the sample application is located in the directory as-install/j2ee14-samples/samples/webservices/security/ejb/apps/xms/ or in a directory of your choice. For easy reference throughout the rest of this section, this directory is referred to as simply app-dir.

  1. Go to the J2EE 1.4 download URL in your browser.

  2. Click on the Download button for the Samples Bundle.

  3. Click on Accept License Agreement.

  4. Click on the J2EE SDK Samples link.

  5. Choose a location for the j2eesdk-1_4_03-samples.zip file.

    Saving the file to as-install is recommended.

  6. Unzip the file.

    Unzipping to the as-install/j2ee14–samples directory is recommended. For example, you can use the following command.


    unzip j2eesdk-1_4_03-samples.zip -d j2ee14-samples

ProcedureTo Run the Sample Application

  1. Make sure that the Application Server is running.

    Message security providers are set up when the asant targets are run, so you do not need to configure these on the Application Server prior to running this example.

  2. If you are not running HTTP on the default port of 8080, change the WSDL file for the example to reflect the change, and change the common.properties file to reflect the change as well.

    The WSDL file for this example is located at app-dir/xms-ejb/src/conf/HelloWorld.wsdl. The port number is in the following section:

    <service name="HelloWorld">
      <port name="HelloIFPort" binding="tns:HelloIFBinding">
        <soap:address location="http://localhost:8080/service/HelloWorld"/>
      </port>
    </service>

    Verify that the properties in the as-install/samples/common.properties file are set properly for your installation and environment. If you need a more detailed description of this file, refer to the “Configuration” section for the web services security applications at as-install/j2ee14–samples/samples/webservices/security/docs/common.html#Logging.

  3. Change to the app-dir directory.

  4. Run the following asant targets to compile, deploy, and run the example application:

    1. To compile samples:

      asant

    2. To deploy samples:

      asant deploy

    3. To run samples:

      asant run

    If the sample has compiled and deployed properly, you see the following response on your screen after the application has run:

    run:[echo] Running the xms program:[exec] Established message level security : Hello Duke!

  5. To undeploy the sample, run the following asant target:


    asant undeploy

    All of the web services security examples use the same web service name (HelloWorld) and web service ports. These examples show only the differences necessary for protecting web services using various mechanisms. Make sure to undeploy an application when you have completed running it. If you do not, you receive an Already in Use error and deployment failures when you try to deploy another web services example application.

Programmatic Login

Programmatic login allows a deployed Java EE application or module 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 Java EE mechanisms. Programmatic login is supported for servlet and EJB components on the server side, and for stand-alone or application clients on the client side. Programmatic login is useful for an application having special needs that cannot be accommodated by any of the Java EE standard authentication mechanisms.


Note –

Programmatic login is specific to the Application Server and not portable to other application servers.


This section contains the following topics:

Programmatic Login Precautions

The 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 security requirements. If the application code reads the authentication information across the network, the application determines 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 using the programmatic login method, access is denied immediately and the application might fail if not coded to account for this occurrence. One way to account for this occurrence is to catch the access control or security exception, perform a programmatic login, and repeat the request.

Granting Programmatic Login Permission

The ProgrammaticLoginPermission permission is required to invoke the programmatic login mechanism for an application if the security manager is enabled. For information about the security manager, see The server.policy File. This permission is not granted by default to deployed applications because this is not a standard Java EE 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.

The ProgrammaticLogin Class

The com.sun.appserv.security.ProgrammaticLogin class enables a user to perform login programmatically.

For Javadoc tool pages relevant to programmatic login, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.security package.

The ProgrammaticLogin class has four login methods, two for servlets or JSP files and two for EJB components.

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

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

The login methods for EJB components have the following signatures:

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

All of these login methods accomplish the following:

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.

If the errors flag is set to true, any exceptions encountered during the login are propagated to the caller. If set to false, exceptions are thrown.

On the client side, realm and errors parameters are ignored and the actual login does not occur until a resource requiring a login is accessed. A java.rmi.AccessException with COBRA NO_PERMISSION occurs if the actual login fails.

The logout methods for servlets or JSP files have the following signatures:

public java.lang.Boolean logout(HttpServletRequest request, 
    HttpServletResponse response)
public java.lang.Boolean logout(HttpServletRequest request, 
    HttpServletResponse response, boolean errors) 
    throws java.lang.Exception

The logout methods for EJB components have the following signatures:

public java.lang.Boolean logout()
public java.lang.Boolean logout(boolean errors) 
    throws java.lang.Exception

All of these logout methods return true if logout succeeded, false if logout failed.

If the errors flag is set to true, any exceptions encountered during the logout are propagated to the caller. If set to false, exceptions are thrown.

User Authentication for Single Sign-on

The single sign-on feature of the Application Server allows multiple web applications deployed to the same virtual server to share the user authentication state. With single sign-on enabled, users who log in to one web application become implicitly logged into other web applications on the same virtual server that require the same authentication information. Otherwise, users would have to log in separately to each web application whose protected resources they tried to access.

A sample 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. After 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="server" ... >
     ...
    <property name="sso-enabled" value="true"/>
     <property name="sso-max-inactive-seconds" value="300"/>
     <property name="sso-reap-interval-seconds" value="60"/>
 </virtual-server>