bea.com | products | dev2dev | support | askBEA

Download Docs | Site Map | Glossary
Search

Programming WebLogic Security

Securing Web Applications

WebLogic Server supports the J2EE architecture security model for securing Web applications, which includes support for declarative authorization (also referred to in this document as declarative security) and programmatic authorization (also referred to in this document as programmatic security).

This section covers the following topics:

- J2EE Security Model

- Authentication With Web Browsers

- Multiple Web Applications, Cookies, and Authentication

- Developing Secure Web Applications

- Using Declarative Security With Web Applications

- Web Application Security-Related Deployment Descriptors

- Using Programmatic Security With Web Applications

- Using the Programmatic Authentication API

Note: You can use deployment descriptor files and the Administration Console to secure Web applications. This document describes how to use deployment descriptor files. For information on using the Administration Console to secure Web applications, see Securing WebLogic Resources.

J2EE Security Model

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., states in Section 9.3 Authorization:

"In the J2EE architecture, a container serves as an authorization boundary between the components it hosts and their callers. The authorization boundary exists inside the container's authentication boundary so that authorization is considered in the context of successful authentication. For inbound calls, the container compares security attributes from the caller's credential with the access control rules for the target component. If the rules are satisfied, the call is allowed. Otherwise, the call is rejected."

"There are two fundamental approaches to defining access control rules: capabilities and permissions. Capabilities focus on what a caller can do. Permissions focus on who can do something. The J2EE application programming model focuses on permissions. In the J2EE architecture, the job of the deployer is to map the permission model of the application to the capabilities of users in the operational environment."

The same document then discusses two ways to control access to application resources using the J2EE architecture, declarative authorization and programmatic authorization.

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., in available online at http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/security/security4.html.

Declarative Authorization

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., states in Section 9.3.1 Authorization:

"The deployer establishes the container-enforced access control rules associated with a J2EE application. The deployer uses a deployment tool to map an application permission model, which is typically supplied by the application assembler, to policy and mechanisms specific to the operational environment. The application permission model is defined in a deployment descriptor."

WebLogic Server supports the use of deployment descriptors to implement declarative authorization in Web applications.

Note: Declarative authorization is also referred to in this document as declarative security.

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., in available online at http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/security/security4.html.

Programmatic Authorization

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., states in Section 9.3.2 Programmatic Authorization:

"A J2EE container makes access control decisions before dispatching method calls to a component. The logic or state of the component doesn't factor in these access decisions. However, a component can use two methods, EJBContext.isCallerInRole (for use by enterprise bean code) and HttpServletRequest.isUserInRole (for use by Web components), to perform finer-grained access control. A component uses these methods to determine whether a caller has been granted a privilege selected by the component based on the parameters of the call, the internal state of the component, or other factors such as the time of the call."

"The application component provider of a component that calls one of these functions must declare the complete set of distinct roleName values to be used in all calls. These declarations appear in the deployment descriptor as security-role-ref elements. Each security-role-ref element links a privilege name embedded in the application as a roleName to a security role. Ultimately, the deployer establishes the link between the privilege names embedded in the application and the security roles defined in the deployment descriptor. The link between privilege names and security roles may differ for components in the same application."

"In addition to testing for specific privileges, an application component can compare the identity of its caller, acquired using EJBContext.getCallerPrincipal or HttpServletRequest.getUserPrincipal, to the distinguished caller identities embedded in the state of the component when it was created. If the identity of the caller is equivalent to a distinguished caller, the component can allow the caller to proceed. If not, the component can prevent the caller from further interaction. The caller principal returned by a container depends on the authentication mechanism used by the caller. Also, containers from different vendors may return different principals for the same user authenticating by the same mechanism. To account for variability in principal forms, an application developer who chooses to apply distinguished caller state in component access decisions should allow multiple distinguished caller identities, representing the same user, to be associated with components. This is recommended especially where application flexibility or portability is a priority."

WebLogic Server supports the use of the HttpServletRequest.isUserInRole and HttpServletRequest.getUserPrincipal methods and the use of the security-role-ref element in deployment descriptors to implement programmatic authorization in Web applications.

Note: Programmatic authorization is also referred to in this document as programmatic security.

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., in available online at http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/security/security4.html.

Declarative Versus Programmatic Authorization

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., states in Section 9.3.3 Declarative Versus Programmatic Authorization:

"There is a trade-off between the external access control policy configured by the deployer and the internal policy embedded in the application by the component provider. The external policy is more flexible after the application has been written. The internal policy provides more flexible functionality while the application is being written. In addition, the external policy is transparent and completely comprehensible to the deployer, while internal policy is buried in the application and may only be completely understood by the application developer. These trade-offs should be considered in choosing the authorization model for particular components and methods."

The document Designing Enterprise Applications with the J2EE Platform, Second Edition, published by Sun Microsystems, Inc., in available online at http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/security/security4.html.

Authentication With Web Browsers

Web browsers can connect to WebLogic Server over either a HyperText Transfer Protocol (HTTP) port or an HTTP with SSL (HTTPS) port. The benefits of using an HTTPS port versus an HTTP port is two-fold. With HTTPS connections:

- All communication on the network between the Web browser and the server is encrypted. None of the communication, including the user name and password, flows in clear text.

- As a minimum authentication requirement, the server is required to present a digital certificate to the Web browser client to prove its identity.

If the server is configured for two-way SSL authentication, both the server and client are required to present a digital certificate to each other to prove their identity.

User Name and Password Authentication

WebLogic Server performs user name and password authentication when users use a Web browser to connect to the server via the HTTP port. In this scenario, the browser and an instance of WebLogic Server interact in the following manner to authenticate a user (see Figure 2-1):

1. A user invokes a WebLogic resource in WebLogic Server by entering the URL for that resource in a Web browser. The URL contains HTTP and the HTTP listen port, for example, http://myserver:7001.

2. The Web server in WebLogic Server receives the request.

   Note: WebLogic Server provides its own Web server but also supports the use of Apache Server, Microsoft Internet Information Server, and Netscape Enterprise Server as Web servers.

3. The Web server checks whether the WebLogic resource is protected by a security policy. If the WebLogic resource is protected, the Web server uses the established HTTP connection to request a user name and password from the user.

4. When the user's Web browser receives the request from the Web server, it prompts the user for a user name and password.

5. The Web browser sends the request to the Web server again, along with the user name and password.

6. The Web server forwards the request to the Web server plug-in. WebLogic Server provides the following plug-ins for Web servers:

   - Apache-WebLogic Server plug-in

   - Netscape Server Application Programming Interface (NSAPI)

   - Internet Information Server Application Programming Interface (ISAPI)

   The Web server plug-in performs authentication by sending the request, via the HTTP protocol, to WebLogic Server, along with the authentication data (user name and password) received from the user.

7. Upon successful authentication, WebLogic Server proceeds to determine whether the user is authorized to access the WebLogic resource.

8. Before invoking a method on the WebLogic resource, the WebLogic Server instance performs a security authorization check. During this check, the server security extracts the user's credentials from the security context, determines the user's security role, compares the user's security role to the security policy for the requested WebLogic resource, and verifies that the user is authorized to invoke the method on the WebLogic resource.

9. If authorization succeeds, the server fulfills the request.

   Figure 2-1 Secure Login for Web Browsers

Digital Certificate Authentication

WebLogic Server uses encryption and digital certificate authentication when Web browser users connect to the server via the HTTPS port. In this scenario, the browser and WebLogic Server instance interact in the following manner to authenticate and authorize a user (see Figure 2-1):

1. A user invokes a WebLogic resource in WebLogic Server by entering the URL for that resource in a Web browser. The URL contains the SSL listen port and the HTTPS schema, for example, https://myserver:7002.

2. The Web server in WebLogic Server receives the request.

   Note: WebLogic Server provides its own Web server but also supports the use of Apache Server, Microsoft Internet Information Server, and Netscape Enterprise Server as Web servers.

3. The Web server checks whether the WebLogic resource is protected by a security policy. If the WebLogic resource is protected, the Web server uses the established HTTPS connection to request a user name and password from the user.

4. When the user's Web browser receives the request from WebLogic Server, it prompts the user for a user name and password. (This step is optional.)

5. The Web browser sends the request again, along with the user name and password. (Only supplied if requested by the server.)

6. WebLogic Server presents its digital certificate to the Web browser.

7. The Web browser checks that the server's name used in the URL (for example, myserver) matches the name in the digital certificate and that the digital certificate was issued by a trusted third party, that is, a trusted CA

8. If two-way SSL authentication is in force on the server, the server requests a digital certificate from the client.

   Note: Even though WebLogic Server cannot be configured to enforce the full two-way SSL handshake with Web Server proxy plug-ins, proxy plug-ins can be configured to provide the client certificate to the server if it is needed. To do this, configure the proxy plug-in to export the client certificate in the HTTP Header for WebLogic Server. For instructions on how to configure proxy plug-ins to export the client certificate to WebLogic Server, see the configuration information for the specific plug-in in Using Web Server Plug-Ins With WebLogic Server.

9. The Web server forwards the request to the Web server plug-in. If secure proxy is set (this is the case if the HTTPS protocol is being used), the Web server plug-in also performs authentication by sending the request, via the HTTPS protocol, to the WebLogic resource in WebLogic Server, along with the authentication data (user name and password) received from the user.

   Note: When using two-way SSL authentication, you can also configure the server to do identity assertion based on the client's certificate, where, instead of supplying a user name and password, the server extracts the user name and password from the client's certificate.

10. Upon successful authentication, WebLogic Server proceeds to determine whether the user is authorized access the WebLogic resource.

11. Before invoking a method on the WebLogic resource, the server performs a security authorization check. During this check, the server extracts the user's credentials from the security context, determines the user's security role, compares the user's security role to the security policy for the requested WebLogic resource, and verifies that the user is authorized to invoke the method on the WebLogic resource.

12. If authorization succeeds, the server fulfills the request.

For more information, see the following documents:

- Managing WebLogic Security

- Installing and Configuring the Apache HTTP Server Plug-In

- Installing and Configuring the Microsoft Internet Information Server (IIS) Plug-In

- Installing and Configuring the Netscape Enterprise Server (NES) Plug-In

Multiple Web Applications, Cookies, and Authentication

By default, WebLogic Server assigns the same cookie name (JSESSIONID) to all Web applications. When you use any type of authentication, all Web applications that use the same cookie name use a single sign-on for authentication. Once a user is authenticated, that authentication is valid for requests to any Web Application that uses the same cookie name. The user is not prompted again for authentication.

If you want to require separate authentication for a Web application, you can specify a unique cookie name or cookie path for the Web application. Specify the cookie name using the CookieName parameter and the cookie path with the CookiePath parameter, defined in the WebLogic-specific deployment descriptor weblogic.xml <session-descriptor> element. For more information, see session-descriptor in Assembling and Configuring Web Applications.

If you want to retain the cookie name and still require independent authentication for each Web application, you can set the cookie path parameter (CookiePath) differently for each Web application.

As of Service Pack 3, BEA Systems added a new capability to WebLogic Server that allows a user to securely access HTTPS resources in a session that was initiated using HTTP, without loss of session data. To enable this new feature, add AuthCookieEnabled="true" to the WebServer element in config.xml:

>     <WebServer Name="myserver" AuthCookieEnabled="true"/>

Setting AuthCookieEnabled to true causes the WebLogic Server instance to send a new secure cookie to the browser when authenticating via an HTTPS connection. Once the secure cookie is set, the session is allowed to access other security-constrained HTTPS resources only if the cookie is sent from the browser.

Note: If authenticating via plain HTTP, the secure cookie is not set or required for any HTTPS resources. When accessing a non-protected HTTPS resource, the cookie is not verified (since it will not have been sent from the browser). This allows the browser to access non-protected HTTPs resources without the user logging in.

Developing Secure Web Applications

WebLogic Server supports three types of authentication for Web browsers:

- BASIC

- FORM

- CLIENT-CERT

The following sections cover these topics:

- Developing BASIC Authentication Web Applications

- Developing FORM Authentication Web Applications

- Using Identity Assertion for Web Application Authentication

- Using Two-Way SSL for Web Application Authentication

- Developing Swing-Based Authentication Web Applications

- Deploying Web Applications

Developing BASIC Authentication Web Applications

With basic authentication, the Web browser pops up a login screen in response to a WebLogic resource request. The login screen prompts the user for a user name and password. Figure 2-2 shows a typical login screen.

Figure 2-2 Basic Authentication Login Screen

To develop a Web application that provides basic authentication, perform these steps:

1. Create the web.xml deployment descriptor. In this file you include the following information (see Listing 2-1):

   1. Define the welcome file. The welcome file name is welcome.jsp.

   2. Define a security constraint for each set of Web application resources, that is, URL resources, that you plan to protect. Each set of resources share a common URL. URL resources such as HTML pages, JSPs, and servlets are the most commonly protected, but other types of URL resources are supported. In Listing 2-1, the URL pattern points to the welcome.jsp file located in the Web application's top-level directory, the HTTP methods that are allowed to access the URL resource, POST and GET, and the security role, webuser, which is specified using the <auth-constraint> tag.

      Note: Be careful to understand and use the <auth-constraint> tag correctly, otherwise, you may not archive the protections you desire. For more information on the <auth-constraint> tag, see auth-constraint. When specifying security role names, observe the following conventions and restrictions:

      - The proper syntax for a security role name is as defined for an Nmtoken in the Extensible Markup Language (XML) recommendation available on the Web at: http://www.w3.org/TR/REC-xml#NT-Nmtoken.

      - Do not use blank spaces, commas, hyphens, or any characters in this comma-separated list: \t, < >, #, |, &, ~, ?, ( ), { }.

      - Security role names are case sensitive.

      - The BEA suggested convention for security role names is that they be singular.

   3. Use the <login-config> to define the type of authentication you want to use and the security realm to which the security constraints will be applied. In Listing 2-1, the BASIC type is specified and the realm is the default realm, which means that the security constraints will apply to the active security realm when the WebLogic Server instance boots.

      Note: In this release of WebLogic Server, the realm name is defined using the <login-config> tag and the <realm-name> sub-tag is ignored.

   4. Define one or more security roles and map them to your security constraints. In our sample, only one security role, webuser, is defined in the security constraint so only one security role name is defined here (see the <security-role> tag in Listing 2-1). However, any number of security roles can be defined.

Listing 2-1 Basic Authentication web.xml File

>     <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

>         <web-app>
>               <welcome-file-list>
>                    <welcome-file>welcome.jsp</welcome-file>
>               </welcome-file-list>

>               <security-constraint>
>                     <web-resource-collection>
>                           <web-resource-name>Success</web-resource-name>
>                           <url-pattern>/welcome.jsp</url-pattern>
>                          <http-method>GET</http-method>
>                          <http-method>POST</http-method>
>                     </web-resource-collection>
>                     <auth-constraint>
>                         <role-name>webuser</role-name>
>                     </auth-constraint>
>               </security-constraint>

>               <login-config>
>                   <auth-method>BASIC</auth-method>
>                   <realm-name>default</realm-name>
>               </login-config>

>                <security-role>
>                    <role-name>webuser</role-name>
>                </security-role>
>         </web-app>

1. Create the weblogic.xml deployment descriptor. In this file you map security role names to users and groups. Listing 2-2 shows a sample weblogic.xml file that maps the webuser security role defined in the <security-role> tag in the companion web.xml file to a group named myGroup. Note that principals can be users or groups, so the <principal-tag> can be used for either.With this configuration, WebLogic Server will only allow users in myGroup to access the protected URL resource—welcome.jsp. However, you can use the Administration Console to modify the Web application's security role so that other groups can be allowed to access the protected resource.

   Note: Creating the weblogic.xml deployment descriptor is optional. If you do not include this file, or include the file but do not include mappings for all security roles, all security roles without mappings will default to any user or group whose name matches the role name. For example, if you name a security role "SampleTester," then any user or group with the name "SampleTester" will be included in that security role.

Listing 2-2 BASIC Authentication weblogic.xml File

>     <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 7.0//EN"
>     "http://www.bea.com/servers/wls700/dtd/weblogic700-web-jar.dtd">

>     <weblogic-web-app>

>          <security-role-assignment>
>              <role-name>webuser</role-name>
>              <principal-name>myGroup</principal-name>
>          </security-role-assignment>

>     </weblogic-web-app>

1. Create a file that produces the Welcome screen that displays when the user enters a user name and password and is granted access. Listing 2-3 shows a sample welcome.jsp file. Figure 2-3 shows the Welcome screen.

Listing 2-3 BASIC Authentication welcome.jsp File

>     <html>
>       <head>
>         <title>Browser Based Authentication Example Welcome Page</title>
>       </head>
>       <h1> Browser Based Authentication Example Welcome Page </h1>

>       <p> Welcome <%= request.getRemoteUser() %>!

>       </blockquote>
>       </body>
>     </html>

Note: In Listing 2-3, notice that the JSP is calling an API (request.getRemoteUser()) to get the name of the user that logged in. A different API, weblogic.security.Security.getCurrentSubject(), could be used instead.

Figure 2-3 Welcome screen

1. Start WebLogic Server and define the users and groups that will have access to the URL resource. In the weblogic.xml file (see Listing 2-2), the <principal-name> tag defines myGroup as the group that has access to the welcome.jsp. Therefore, use the Administration Console to define the myGroup group, define a user, and add that user to the myGroup group. For information on adding users and groups, see Users and Groups in Securing WebLogic Resources.

2. Deploy the Web application and use the user defined in the previous step to access the protected URL resource.

   1. For deployment instructions, see "Deploying Web Applications" on page 2-26.

   2. Open a Web browser and enter this URL:

      http://localhost:7001/basicauth/welcome.jsp

   3. Enter the user name and password. The Welcome screen displays.

Using HttpSessionListener to Account for Browser Caching of Credentials

The browser caches user credentials and frequently resends them to the server automatically. This can give the appearance that WebLogic Server sessions are not being destroyed after logout or timeout. Depending on the browser, the credentials can be cached just for the current browser session, or across browser sessions.

You can validate that a WebLogic Server's session was destroyed by creating a class that implements the javax.servlet.http.HttpSessionListener interface. Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application in web.xml.

To configure a session listener class:

1. Open the web.xml deployment descriptor of the Web application for which you are creating a session listener class in a text editor. The web.xml file is located in the WEB-INF directory of your Web application.

2. Add an event declaration using the listener element of the web.xml deployment descriptor. The event declaration defines the event listener class that is invoked when the event occurs. For example:
   <listener>
   <listener-class>myApp.MySessionListener</listener-class>
   </listener>
   See Configuring an Event Listener Class for additional information and guidelines.

Write and deploy the session listener class. The example shown in Listing 2-4 uses a simple counter to track the session count.

Listing 2-4 Tracking the Session Count

>     package myApp;

>     import javax.servlet.http.HttpSessionListener;
>     import javax.servlet.http.HttpSessionEvent;

>     public class MySessionListener implements HttpSessionListener {

>            private static int sessionCount = 0;

>            public void sessionCreated(HttpSessionEvent se) {
>                    sessionCount++;
>                     // Write to a log or do some other processing.
>            }

>            public void sessionDestroyed(HttpSessionEvent se) {
>                     if(sessionCount > 0)
>                              sessionCount--;
>                          //Write to a log or do some other processing.
>                }

>     }

Developing FORM Authentication Web Applications

When using FORM authentication with Web applications, you provide a custom login screen that the Web browser displays in response to a Web application resource request and an error screen that displays if the login fails. The login screen can be generated using an HTML page, JSP, or servlet. The benefit of form-based login is that you have complete control over these screens so that you can design them to meet the requirements of your application or enterprise policy/guideline.

The login screen prompts the user for a user name and password. Figure 2-4 shows a typical login screen generated using a JSP and Listing 2-5 shows the source code.

Figure 2-4 Form-Based Login Screen (login.jsp)

Listing 2-5 Form-Based Login Screen Source Code (login.jsp)

>     <html>
>       <head>)
>         <title>Security WebApp login page</title>
>       </head>
>       <body bgcolor="#cccccc">
>       <blockquote>
>       <img src=BEA_Button_Final_web.gif align=right>
>       <h2>Please enter your user name and password:</h2>
>       <p>
>       <form method="POST" action="j_security_check">
>       <table border=1>
>         <tr>
>           <td>Username:</td>
>           <td><input type="text" name="j_username"></td>
>         </tr>
>         <tr>
>           <td>Password:</td>
>           <td><input type="password" name="j_password"></td>
>         </tr>
>         <tr>
>           <td colspan=2 align=right><input type=submit
>                                          value="Submit"></td>
>         </tr>
>       </table>
>       </form>
>       </blockquote>
>       </body>
>     </html>

Figure 2-5 shows a typical login error screen generated using HTML and Listing 2-6 shows the source code.

Figure 2-5 Login Error Screen

Listing 2-6 Login Error Screen Source Code

>     <html>
>       <head>
>         <title>Login failed</title>
>       </head>
>       <body bgcolor=#ffffff>
>       <blockquote>
>       <img src=/security/BEA_Button_Final_web.gif align=right>
>       <h2>Sorry, your user name and password were not recognized.</h2>
>       <p><b>
>       <a href="/security/welcome.jsp">Return to welcome page</a> or
>                <a href="/security/logout.jsp">logout</a>
>       </b>
>       </blockquote>
>       </body>
>     </html>

To develop a Web application that provides FORM authentication, perform these steps:

1. Create the web.xml deployment descriptor. In this file you include the following information (see Listing 2-7):

   1. Define the welcome file. The welcome file name is welcome.jsp.

   2. Define a security constraint for each set of Web application resources, that is, the URL resources, that you plan to protect. Each set of URL resources share a common URL. URL resources such as HTML pages, JSPs, and servlets are the most commonly protected, but other types of URL resources are supported. In Listing 2-7, the URL pattern points to /admin/edit.jsp, thus protecting the edit.jsp file located in the Web application's admin sub-directory, defines the HTTP method that is allowed to access the URL resource, GET, and defines the security role name, admin, which is specified using the <auth-constraint> tag.

      Note: Be careful to understand and use the <auth-constraint> tag correctly, otherwise, you may not archive the protections you desire. For more information on the <auth-constraint> tag, see auth-constraint. When specifying security role names, observe the following conventions and restrictions:

      - The proper syntax for a security role name is as defined for an Nmtoken in the Extensible Markup Language (XML) recommendation available on the Web at: http://www.w3.org/TR/REC-xml#NT-Nmtoken.

      - Do not use blank spaces, commas, hyphens, or any characters in this comma-separated list: \t, < >, #, |, &, ~, ?, ( ), { }.

      - Security role names are case sensitive.

      - The BEA suggested convention for security role names is that they be singular.

   3. Define the type of authentication you want to use and the security realm to which the security constraints will be applied. In this case, the FORM type is specified and no realm is specified, so the realm is the default realm, which means that the security constraints will apply to the security realm that is activated when a WebLogic Server instance boots.

   4. Define one or more security roles and map them to your security constraints. In our sample, only one security role, admin, is defined in the security constraint so only one security role name is defined here. However, any number of security roles can be defined.

Listing 2-7 FORM Authentication web.xml File

>     <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

>     <web-app>

>         <welcome-file-list>
>             <welcome-file>welcome.jsp</welcome-file>
>         </welcome-file-list>

>         <security-constraint>
>             <web-resource-collection>
>                 <web-resource-name>AdminPages</web-resource-name>
>                 <description>
>                     These pages are only accessible by authorized
>                      administrators.
>                 </description>
>                 <url-pattern>/admin/edit.jsp</url-pattern>
>                 <http-method>GET</http-method>
>             </web-resource-collection>
>             <auth-constraint>
>                 <description>
>                     These are the roles who have access.
>                 </description>
>                 <role-name>
>                     admin
>                 </role-name>
>             </auth-constraint>
>             <user-data-constraint>
>                 <description>
>                     This is how the user data must be transmitted.
>                 </description>
>                 <transport-guarantee>NONE</transport-guarantee>
>             </user-data-constraint>
>         </security-constraint>

>         <login-config>
>             <auth-method>FORM</auth-method>
>             <form-login-config>
>                 <form-login-page>/login.jsp</form-login-page>
>                 <form-error-page>/fail_login.html</form-error-page>
>             </form-login-config>
>         </login-config>

>         <security-role>
>             <description>
>                 An administrator
>             </description>
>             <role-name>
>                 admin
>             </role-name>
>         </security-role>
>     </web-app>

1. Create the weblogic.xml deployment descriptor. In this file you map security role names to users and groups. Listing 2-8 shows a sample weblogic.xml file that maps the admin security role defined in the <security-role> tag in the companion web.xml file to the group supportGroup. With this configuration, WebLogic Server will only allow users in the supportGroup group to access the protected WebLogic resource. However, you can use the Administration Console to modify the Web application's security role so that other groups can be allowed to access the protected WebLogic resource.

Listing 2-8 FORM Authentication weblogic.xml File

>     <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 7.0//EN"
>     "http://www.bea.com/servers/wls700/dtd/weblogic700-web-jar.dtd">

>     <weblogic-web-app>

>          <security-role-assignment>
>              <role-name>admin</role-name>
>              <principal-name>supportGroup</principal-name>
>          </security-role-assignment>

>     </weblogic-web-app>

1. Create a Web application file that produces the welcome screen when the user requests the protected Web application resource by entering the URL. Listing 2-9 shows a sample welcome.jsp file. Figure 2-3 shows the Welcome screen.

Listing 2-9 Form Authentication welcome.jsp File

>     <html>
>       <head>
>         <title>Security login example</title>
>       </head>

>       <%
>         String bgcolor;
>         if ((bgcolor=(String)application.getAttribute("Background")) ==
>             null)
>         {
>             bgcolor="#cccccc";
>         }
>       %>

>       <body bgcolor=<%="\""+bgcolor+"\""%>>

>       <blockquote>
>       <img src=BEA_Button_Final_web.gif align=right>
>       <h1> Security Login Example </h1>

>       <p> Welcome <%= request.getRemoteUser() %>!

>       <p> If you are an administrator, you can configure the background
>       color of the Web Application.
>       <br> <b><a href="admin/edit.jsp">Configure background</a></b>.

>       <% if (request.getRemoteUser() != null) { %>
>         <p> Click here to <a href="logout.jsp">logout</a>.
>       <% } %>

>       </blockquote>
>       </body>
>     </html>

Note: In Listing 2-9, notice that the JSP is calling an API (request.getRemoteUser()) to get the name of the user that logged in. A different API, weblogic.security.Security.getCurrentSubject(), could be used instead.

1. Start WebLogic Server and define the users and groups that will have access to the URL resource. In the weblogic.xml file (see Listing 2-8), the <role-name> tag defines admin as the group that has access to the edit.jsp, file and defines the user joe as a member of that group. Therefore, use the Administration Console to define the admin group, and define user joe and add joe to the admin group. You can also define other users and add them to the group, and they will also have access to the protected WebLogic resource. For information on adding users and groups, see Users and Groups in Securing WebLogic Resources.

2. Deploy the Web application and use the user(s) defined in the previous step to access the protected Web application resource.

   1. For deployment instructions, see "Deploying Web Applications" on page 2-26.

   2. Open a Web browser and enter this URL:

      http://hostname:7001/security/welcome.jsp

   3. Enter the user name and password. The Welcome screen displays.

Using Identity Assertion for Web Application Authentication

You use identity assertion in Web applications to verify client identities for authentication purposes. When using identity assertion, the following requirements must be met:

1. The authentication type must be set to CLIENT-CERT.

2. An Identity Assertion provider must be configured in the server. If the Web browser or Java client requests a WebLogic Server resource protected by a security policy, WebLogic Server requires that the Web browser or Java client have an identity. The WebLogic Identity Assertion provider maps the token from a Web browser or Java client to a user in a WebLogic Server security realm. For information on how to configure an Identity Assertion provider, see Configuring a WebLogic Identity Assertion Provider.

3. The user corresponding to the token's value must be defined in the server's security realm; otherwise the client will not be allowed to access a protected WebLogic resource. For information on configuring users on the server, see Creating Users in Managing WebLogic Security.

Using Two-Way SSL for Web Application Authentication

You use two-way SSL in Web applications to verify that clients are whom they claim to be. When using two-way SSL, the following requirements must be met:

1. The authentication type must be set to CLIENT-CERT.

2. The server must be configured for two-way SSL. For information on using SSL and digital certificates, see Using SSL Authentication in Java Clients. For information on configuring SSL on the server, see Configuring SSL in Managing WebLogic Security.

3. The client must use HTTPS to access the Web application on the server.

4. An Identity Assertion provider must be configured in the server. If the Web browser or Java client requests a WebLogic Server resource protected by a security policy, WebLogic Server requires that the Web browser or Java client have an identity. The WebLogic Identity Assertion provider allows you to enable a user name mapper in the server that maps the digital certificate of a Web browser or Java client to a user in a WebLogic Server security realm. For information on how to configure an Identity Assertion provider and a user name mapper, see Configuring a WebLogic Identity Assertion Provider and Configuring a User Name Mapper in Managing WebLogic Security.

5. The user corresponding to the Subject's Distinguished Name (SubjectDN) attribute in the client's digital certificate must be defined in the server's security realm; otherwise the client will not be allowed to access a protected WebLogic resource. For information on configuring users on the server, see Creating Users in Managing WebLogic Security.

Note: When you use SSL authentication, it is not necessary to use web.xml and weblogic.xml files to specify server configuration because you use the Administration Console to specify the server's SSL configuration. For information on configuring SSL on the server, see Configuring SSL in Managing WebLogic Security.

Developing Swing-Based Authentication Web Applications

Web browsers can also be used to run graphical user interfaces (GUIs) that were developed using Swing components. The Swing components, which are part of the Java Foundation Classes (JFC), can be used with either JDK 1.1 or the Java 2 platform.

For information on how to create a graphical user interface (GUI) for applications and applets using the Swing components, see the Creating a GUI with JFC/Swing tutorial (also known as The Swing Tutorial) produced by Sun Microsystems, Inc. You can access this tutorial on the Web at http://java.sun.com/docs/books/tutorial/uiswing/.

After you have developed your Swing-based GUI, refer to Developing FORM Authentication Web Applications and use the Swing-based screens to perform the steps required to develop a Web application that provides FORM authentication.

Note: When developing a Swing-based GUI, do not rely on the Java Virtual Machine-wide user for child threads of the swing event thread. This is not J2EE compliant and does not work in thin clients, or in IIOP in general. Instead, take either of the following approaches:

- Make sure an InitialContext is created before any Swing artefacts.

- Or, use the Java Authentication and Authorization Service (JAAS) to login and then use the Security.runAs() method inside the Swing event thread and its children.

Deploying Web Applications

To deploy a Web application on a server running in development mode, perform the following steps:

Note: For more information about deploying Web applications in either development of production mode, see Deploying Web Applications in Developing Web Applications for WebLogic Server.

1. Set up a directory structure for the Web application's files. Figure 2-6 shows the directory structure for the Web application named basicauth. The top-level directory must be assigned the name of the Web application and the sub-directory must be named WEB-INF.

   Figure 2-6 Basicauth Web Application Directory Structure

2. To deploy the Web application in exploded directory format, that is, not in the Java archive (jar) format, simply move your directory to the applications directory on your server. For example, you would deploy the basicauth Web application in the following location:

   WL_HOME\user_projects\mydomain\applications\basicauth

   If the WebLogic Server instance is running, the application should auto-deploy. Use the Administration Console to verify that the application deployed.

   If the WebLogic Server instance is not running, the Web application should auto-deploy when you start the server.

3. If you have not done so already, use the Administration Console to configure the users and groups that will have access to the Web application. To determine the users and groups that are allowed access to the protected WebLogic resource, examine the weblogic.xml file. For example, the weblogic.xml file for the basicauth sample (see Listing 2-2) defines myGroup as the only group to have access to the welcome.jsp file.

For more information on deploying secure Web applications, see Deploying Web Applications in Developing Web Applications for WebLogic Server.

Using Declarative Security With Web Applications

To implement declarative security in Web applications, you use deployment descriptors (web.xml and weblogic.xml) to define security requirements. The deployment descriptors map the application's logical security requirements to its runtime definitions. And at runtime, the servlet container uses the security definitions to enforce the requirements.

For a discussion of using deployment descriptors in to configure security in simple web applications, see Developing Secure Web Applications.

For a description of all security-related deployment descriptors, see Web Application Security-Related Deployment Descriptors.

For information about how to use the Administration Console to configure security in Web applications, see Securing WebLogic Resources.

Web Application Security-Related Deployment Descriptors

The following topics describe the deployment descriptor elements that are used in the web.xml and weblogic.xml files to define security requirements in Web applications:

- Web.xml Deployment Descriptors

- Weblogic.xml Deployment Descriptors

Web.xml Deployment Descriptors

The following web.xml security-related deployment descriptor elements are used to define security requirements in WebLogic Server::

- auth-constraint

- security-constraint

- security-role

- security-role-ref

- user-data-constraint

- web-resource-collection

The information in this section is based on the Document Type Descriptor (DTD) for web.xml provided by Sun Microsystems, Inc. The DTD for web.xml is available on the Web at http://java.sun.com/dtd/web-app_2_3.dtd.

auth-constraint

The optional auth-constraint element defines which groups or principals have access to the collection of Web resources defined in this security constraint.

Note: An authorization constraint, which is defined using the <auth-constraint> tag, establishes a requirement for authentication and names the authorization roles, or security roles, permitted to perform the constrained requests. When you use the <auth-constraint> tag to define an authorization constraint, be advised of the following:

- If you define an authorization constraint that does not name any security roles, the container will not allow access to the constrained requests under any circumstances.

- If no authorization constraint applies to a request, the container must accept the request without requiring user authentication.

The following examples illustrate how to use the <auth-constraint> tag:

- Example 1: Using the <security-constraint> Tag Without the <auth-constraint> tag

- Example 2: Using the <auth-constraint> Tag Without Specifying a Role

- Example 3: Using the <auth-constraint> Tag With a Specified Role

For more information on using the <auth-constraint> tag, see the Java Servlet Specification Version 2.4 specification located on the Internet at http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html.

The following table describes the elements you can define within an auth-constraint element.

Element | Required/ Optional | Description
--- | --- | ---
<description> | Optional | A text description of this security constraint.
<role-name> | Optional | Defines which security roles can access resources defined in this security-constraint. Security role names are mapped to principals using the security-role-ref element. See security-role-ref.

Used Within

The auth-constraint element is used within the security-constraint element.

Example 1: Using the <security-constraint> Tag Without the <auth-constraint> tag

Listing 2-10 illustrates a resource that is not checked and that is unprotected. In this case there is no <auth-constraint> tag used so the resource is unchecked/unprotected. This type of protection is useful when you have everything protected ("/*"), but you want to allow free access to static files or images.

Listing 2-10 Case 1: Unchecked and Unprotected Resource

>     <security-constraint>
>         <web-resource-collection>
>           <web-resource-name>Unchecked-Resource</web-resource-name>
>           <url-pattern>/foo/*</url-pattern>
>         </web-resource-collection>
>     </security-constraint>

Example 2: Using the <auth-constraint> Tag Without Specifying a Role

Listing 2-11 illustrates using the <auth-constraint> tag that does not specify a role, so the resource is inaccessible for everybody. Using the <auth-constraint> tag in this way is useful in the cases where you want to avoid direct access to the resource, but you want to allow forwards, includes, servletContext.getResource(), getResourceAsStream() to access it.

Note: An alternative to using the <auth-constraint> tag this way is to put the resources under the WEB-INF directory because WebLogic Server does not allow direct requests to access resources under that directory

Listing 2-11 The <auth-constraint> Tag With No Role Specified

>       <security-constraint>
>         <web-resource-collection>
>           <web-resource-name>Excluded-Resource</web-resource-name>
>           <url-pattern>/foo/*</url-pattern>
>         </web-resource-collection>
>         <auth-constraint>
>         </auth-constraint>
>       </security-constraint>

Example 3: Using the <auth-constraint> Tag With a Specified Role

Listing 2-12 illustrates using the <auth-constraint> tag with a role specified. In this case the resource is checked/protected/secured and will be accessible only by users in adminrole role.

Listing 2-12 The <auth-constraint> Tag With a Role Specified

>       <security-constraint>
>         <web-resource-collection>
>           <web-resource-name>Checked-Resource</web-resource-name>
>           <url-pattern>/blah/*</url-pattern>
>         </web-resource-collection>
>         <auth-constraint>
>           <role-name>adminrole</role-name>
>         </auth-constraint>
>       </security-constraint>

security-constraint

The security-constraint element is use in the web.xml file to define the access privileges to a collection of resources defined by the web-resource-collection element.

The following table describes the elements you can define within a security-constraint element.

Element | Required/ Optional | Description
--- | --- | ---
<web-resource- collection> | Required | Defines the components of the Web Application to which this security constraint is applied. For more information, see web-resource-collection.
<auth-constraint> | Optional | Defines which groups or principals have access to the collection of web resources defined in this security constraint. For more information, see auth-constraint.
<user-data- constraint> | Optional | Defines defines how data communicated between the client and the server should be protected. For more information, see user-data-constraint

Example

Listing 2-13 shows how to use the security-constraint element to defined security for the SecureOrdersEast in a web.xml file.

Listing 2-13 Security Constraint Example

>     web.xml entries:
>     <security-constraint>
>          <web-resource-collection>
>               <web-resource-name>SecureOrdersEast</web-resource-name>
>               <description>
>                  Security constraint for
>                  resources in the orders/east directory
>               </description>
>               <url-pattern>/orders/east/*</url-pattern>
>               <http-method>POST</http-method>
>               <http-method>GET</http-method>
>          </web-resource-collection>
>          <auth-constraint>
>               <description>
>                constraint for east coast sales
>               </description>
>               <role-name>east</role-name>
>               <role-name>manager</role-name>
>          </auth-constraint>
>      <user-data-constraint>
>               <description>SSL not required</description>
>               <transport-guarantee>NONE</transport-guarantee>
>          </user-data-constraint>
>     </security-constraint>
>     ...

security-role

The security-role element contains the definition of a security role. The definition consists of an optional description of the security role, and the security role name.

The following table describes the elements you can define within a security-role element.

Element | Required/ Optional | Description
--- | --- | ---
<description> | Optional | A text description of this security role.
<role-name> | Required | The role name. The name you use here must have a corresponding entry in the WebLogic-specific deployment descriptor, weblogic.xml, which maps roles to principals in the security realm. For more information, see security-role-assignment.

Example

See Listing 2-1 for an example of how to use the security-role element in a web.xml file.

security-role-ref

The security-role-ref element links a security role name defined by <security-role> to an alternative role name that is hard-coded in the servlet logic. This extra layer of abstraction allows the servlet to be configured at deployment without changing servlet code.

The following table describes the elements you can define within a security-role-ref element.

Element | Required/ Optional | Description
--- | --- | ---
<description> | Optional | Text description of the role.
<role-name> | Required | Defines the name of the security role or principal that is used in the servlet code.
<role-link> | Required | Defines the name of the security role that is defined in a <security-role> element later in the deployment descriptor.

Example

See Listing 2-18 for an example of how to use the security-role-ref element in a web.xml file.

user-data-constraint

The user-data-constraint element defines how data communicated between the client and the server should be protected.

The following table describes the elements you may define within a user-data-constraint element.

Element | Required/ Optional | Description
--- | --- | ---
<description> | Optional | A text description.
<transport- guarantee> | Required | Specifies data security requirements for communications between the client and the server. Range of values: NONE—The application does not require any transport guarantees. INTEGRAL—The application requires that the data be sent between the client and server in such a way that it cannot be changed in transit. CONFIDENTIAL—The application requires that data be transmitted so as to prevent other entities from observing the contents of the transmission. Note: WebLogic Server establishes a Secure Sockets Layer (SSL) connection when the user is authenticated using the INTEGRAL or CONFIDENTIAL transport guarantee.

Used Within

The user-data-constraint element is used within the security-constraint element.

Example

See Listing 2-13 for an example of how to use the user-data-constraint element in a web.xml file.

web-resource-collection

The web-resource-collection element is used to identify a subset of the resources and HTTP methods on those resources within a Web application to which a security constraint applies. If no HTTP methods are specified, then the security constraint applies to all HTTP methods.

The following table describes the elements you can define within a web-resource-collection element.

Element | Required/ Optional | Description
--- | --- | ---
<web-resource-name> | Required | The name of this web resource collection.
<description> | Optional | Text description of the Web resource.
<url-pattern> | Required | The mapping, or location, of the Web resource collection.
<http-method> | Optional | The HTTP methods to which the security constraint applies when clients attempt to access the Web resource collection. If no HTTP methods are specified, then the security constraint applies to all HTTP methods.

Used Within

The web-resource-collection element is used within the security-constraint element.

Example

See Listing 2-13 for an example of how to use the web-resource-collection element in a web.xml file.

Weblogic.xml Deployment Descriptors

The following weblogic.xml security-related deployment descriptor elements are used to define security requirements in WebLogic Server:

- global-role

- security-permission

- security-permission-spec

- security-role-assignment

For additional information on weblogic.xml deployment descriptions, see the Document Type Descriptor (DTD) for weblogic.xml at http://www.bea.com/servers/wls700/dtd/weblogic700-web-jar.dtd.

global-role

In WebLogic Server 7.0 SP1 and later, the global-role element is used to explicitly indicate that you want the particular security roles defined by role-name elements in the companion web.xml file to use the mappings that you specify in the Administration Console. This element is used as an indicative placeholder instead of a set of principal-name elements.

The global-role element gives you the flexibility of not having to specify a specific security role mapping for each security role defined in the deployment descriptors for a particular Web application. Rather, you can use the Administration Console to specify and modify a specific role mapping for each defined role at anytime. Additionally, because you may elect to use this element on some applications and not others, it is not necessary to check the Ignore Security Data In Deployment Descriptors attribute on the General tab of the security realm. Therefore, within the same security realm, deployment descriptors can be used to specify and modify security for some applications while the Administration Console can be used to specify and modify security for others.

Note: When specifying security role names, observe the following conventions and restrictions:

- The proper syntax for a security role name is as defined for an Nmtoken in the Extensible Markup Language (XML) recommendation available on the Web at: http://www.w3.org/TR/REC-xml#NT-Nmtoken.

- Do not use blank spaces, commas, hyphens, or any characters in this comma-separated list: \t, < >, #, |, &, ~, ?, ( ), { }.

- Security role names are case sensitive.

- The BEA suggested convention for security role names is that they be singular.

Used Within

The global-role element is used within the security-role-assignment element.

Example

Listing 2-14 and Listing 2-15 show by comparison how to use the global-role element in a weblogic.xml file. In Listing 2-15, the specification of the "webuser" global-role element in the weblogic-ejb-jar.xml means that for security to be correctly configured on the getReceipts method, the principals for webuser will have to be created in the Administration Console.

Listing 2-14 Using the web.xml and weblogic.xml Files to Map Security Roles and Principals to a Security Realm

>     web.xml entries:

>     <web-app>
>                ...
>                <security-role>
>                    <role-name>webuser</role-name>
>                </security-role>
>                ...

>     </web-app>

>     <weblogic.xml entries:

>     <weblogic-web-app>

>          <security-role-assignment>
>              <role-name>webuser</role-name>
>              <principal-name>myGroup</principal-name>
>              <principal-name>Bill</principal-name>
>              <principal-name>Mary</principal-name>
>          </security-role-assignment>

>     </weblogic-web-app>

Listing 2-15 Using the global-role Element in Web Application Deployment Descriptors

>     web.xml entries:

>     <web-app>
>                ...
>                <security-role>
>                    <role-name>webuser</role-name>
>                </security-role>
>                ...

>     </web-app>

>     <weblogic.xml entries:

>     <weblogic-web-app>

>          <security-role-assignment>
>              <role-name>webuser</role-name>
>              <global-role/>
>          </security-role-assignment>

For information about how to use the Administration Console to configure security for Web applications, see Securing WebLogic Resources.

security-permission

The security-permission element specifies a security permission that is associated with a J2EE Sandbox.

Example

For an example of how to used the security-permission element, see Listing 2-16.

security-permission-spec

The security-permission-spec element specifies a single security permission based on the Security policy file syntax. Refer to the following URL for Sun's implementation of the security permission specification:

http://java.sun.com/j2se/1.3/docs/guide/security/PolicyFiles.html#FileSyntax

Note: Disregard the optional codebase and signedBy clauses.

Used Within

The security-permission-spec element is used within the security-permission element.

Example

Listing 2-16 shows how to use the security-permission-spec element to grant permission to the java.net.SocketPermission class.

Listing 2-16 security-permission-spec Element Example

>     <weblogic-web-app>
>        <security-permission>
>          <description>Optional explanation goes here</description>
>          <security-permission-spec>
>     <!—
>     A single grant statement following the syntax of http://java.sun.com/j2se/1.3/docs/guide/security/PolicyFiles.html#FileSyntax, without the "codebase" and "signedBy" clauses, goes here. For example:
>     -->
>           grant {
>           permission java.net.SocketPermission "*", "resolve";
>           };
>          </security-permission-spec>
>        </security-permission>
>     </weblogic-web-app>

In Listing 2-16, permission java.net.SocketPermission is the permission class name, "*" represents the target name, and resolve (resolve host/ip name service lookups) indicates the action.

security-role-assignment

The security-role-assignment element declares a mapping between a security role and one or more principals in the WebLogic Server security realm,

Example

Listing 2-17 shows how to use the security-role-assignment element to assign principals to the PayrollAdmin role.

Listing 2-17 security-role-assignment Element Example

>     <weblogic-web-app>
>       <security-role-assignment>
>             <role-name>PayrollAdmin</role-name>
>            <principal-name>Tanya</principal-name>
>            <principal-name>Fred</principal-name>
>            <principal-name>system</principal-name>
>       </security-role-assignment>
>     </weblogic-web-app>

Using Programmatic Security With Web Applications

You can write your servlets to access users and security roles programmatically in your servlet code. To do this, use the following methods in your servlet code: javax.servlet.http.HttpServletRequest.getUserPrincipal and javax.servlet.http.HttpServletRequest.isUserInRole(String role) methods.

getUserPrincipal

You use the getUserPrincipal() method to determine the current user of the Web application. This method returns a WLSUser Principal if one exists in the current user. In the case of multiple WLSUser Principals, the method returns the first in the ordering defined by the Subject.getPrincipals().iterator() method. If there are no WLSUser Principals, then the getUserPrincipal() method returns the first non-WLSGroup Principal. If there are no Principals or all Principals are of type WLSGroup, this method returns null. This behavior is identical to the semantics of the weblogic.security.SubjectUtils.getUserPrincipal() method.

For more information about how to use the getUserPrincipal() method, see http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Security4.html.

isUserInRole

The javax.servlet.http.HttpServletRequest.isUserInRole(String role) method returns a boolean indicating whether the authenticated user is granted the specified logical security "role." If the user has not been authenticated, this method returns false.

The isUserInRole()method maps security roles to the group names in the security realm. Listing 2-18 shows the elements that are used with the <servlet> element to define the security role in the companion web.xml file.

Listing 2-18 IsUserInRole web.xml and weblogic.xml Elements

>     Begin web.xml entries:

>     ...
>     <servlet>
>             <security-role-ref>
>                  <role-name>user-rolename</role-name>
>                  <role-link>rolename-link</role-link>
>             </security-role-ref>
>     </servlet>

>     <security-role>
>              <role-name>rolename-link</role-name>
>     </security-role>
>     ...

>     Begin weblogic.xml entries:

>     ...
>     <security-role-assignment>
>              <role-name>rolename-link</role-name>
>              <principal-name>groupname</principal>
>              <principal-name>username</principal>
>     </security-role-assignment>
>     ...

The string role is mapped to the name supplied in the <role-name> element, which is nested inside the <security-role-ref> element of a <servlet> declaration in the companion web.xml deployment descriptor. The <role-name> element defines the name of the security role or principal (the user or group) that is used in the servlet code. The <role-link> element maps to a <role-name> defined in the <security-role-assignment> element in the weblogic.xml deployment descriptor.

Note: When specifying security role names, observe the following conventions and restrictions:

- The proper syntax for a security role name is as defined for an Nmtoken in the Extensible Markup Language (XML) recommendation available on the Web at: http://www.w3.org/TR/REC-xml#NT-Nmtoken.

- Do not use blank spaces, commas, hyphens, or any characters in this comma-separated list: \t, < >, #, |, &, ~, ?, ( ), { }.

- Security role names are case sensitive.

- The BEA suggested convention for security role names is that they be singular.

For example, if the client has successfully logged in as user Bill with the security role of manager, the following method would return true:

>     request.isUserInRole("manager")

Listing 2-19 provides an example.

Listing 2-19 Example of Security Role Mapping

>     Servlet code:
>     out.println("Is the user a Manager? " +
>                              request.isUserInRole("manager"));

>     web.xml entries:

>     <servlet>
>     . . .
>        <role-name>manager</role-name>
>        <role-link>mgr</role-link>
>     . . .
>     </servlet>

>     <security-role>
>        <role-name>mgr</role-name>
>     </security-role>

>     weblogic.xml entries:

>     <security-role-assignment>
>        <role-name>mgr</role-name>
>        <principal-name>bostonManagers</principal-name>
>        <principal-name>Bill</principal-name>
>        <principal-name>Ralph</principal-name>
>     </security-role-ref>

Using the Programmatic Authentication API

There are some applications where programmatic authentication is appropriate.

WebLogic Server provides a server-side API that supports programmatic authentication from within a servlet application:

>     weblogic.servlet.security.ServletAuthentication

Using this API, you can write servlet code that authenticates the user, logs in the user, and associates the user with the current session so that the user is registered in the default (active) security realm. Once the login is completed, it appears as if the user logged in using the standard mechanism.

You have the option of using either of two WebLogic-supplied classes with the ServletAuthentication API, the weblogic.security.SimpleCallbackHandler class or the weblogic.security.URLCallbackHandler class. For more information on these classes, see Javadocs for WebLogic Classes.

Listing 2-20 shows an example that uses SimpleCallbackHandler. Listing 2-21 shows an example that uses URLCallbackHandler.

Listing 2-20 Programmatic Authentication Code Fragment Using the SimpleCallbackHandler Class

>     CallbackHandler handler = new SimpleCallbackHandler(username, password);
>     Subject mySubject = weblogic.security.services.Authentication.login(handler);
>     weblogic.servlet.security.ServletAuthentication.runAs(mySubject, request);

Where request is the httpservletrequest object.

Listing 2-21 Programmatic Authentication Code Fragment Using the URLCallbackHandler Class

>     CallbackHandler handler = new URLCallbackHandler(username, password);
>     Subject mySubject = weblogic.security.services.Authentication.login(handler);
>     weblogic.servlet.security.ServletAuthentication.runAs(mySubject, request);

>     Where request is the httpservletrequest object.