Authentication 254J2EE Users, Realms, and Groups 255Authentication Mechanisms 257Controlling Access to J2EE Resources 259Client Authentication 260Web Client Authentication 261Application
Trang 1The source code for the following example is in theexamples/src/ejb/teller
directory To compile the code, go to theexamples/srcdirectory and typeant teller To create the database tables, typeant create-bank-teller
To demarcate a JTA transaction, you invoke thebegin, commit, and rollback
methods of theUserTransactioninterface The following code, taken from the
TellerEJBexample program, demonstrates theUserTransactionmethods The
beginandcommitinvocations delimit the updates to the database If the updatesfail, the code invokes therollback method and throws anEJBException
public void withdrawCash(double amount) {
UserTransaction ut = context.getUserTransaction();
try { ut.begin();
throw new EJBException (“Transaction failed: “ + ex.getMessage());
} }
Returning Without Committing
In a stateless session bean with bean-managed transactions, a business methodmust commit or roll back a transaction before returning However, a stateful ses-sion bean does not have this restriction
In a stateful session bean with a JTA transaction, the association between thebean instance and the transaction is retained across multiple client calls Even ifeach business method called by the client opens and closes the database connec-tion, the association is retained until the instance completes the transaction
Trang 2S UMMARY OF T RANSACTION O PTIONS 247
In a stateful session bean with a JDBC transaction, the JDBC connection retainsthe association between the bean instance and the transaction across multiplecalls If the connection is closed, the association is not retained
Methods Not Allowed in Bean-Managed Transactions
Do not invoke the getRollbackOnly and setRollbackOnly methods of the
EJBContextinterface These methods should be used only in container-managedtransactions For bean-managed transactions you invoke the getStatus and
rollback methods of theUserTransaction interface
Summary of Transaction Options
The decision tree in Figure 17 shows the different approaches to transactionmanagement that you may take Your first choice depends on whether the enter-prise bean is an entity or a session bean An entity bean must use container-man-aged transactions With container-managed transactions, you specify thetransaction attributes in the deployment descriptor and you roll back a transac-tion with thesetRollbackOnlymethod of theEJBContextinterface A sessionbean may have either container-managed or bean-managed transactions Thereare two types of bean-managed transactions: JDBC and JTA transactions Youdelimit JDBC transactions with thecommitandrollbackmethods of theCon- nectioninterface To demarcate JTA transactions, you invoke the begin, com- mit, androllback methods of theUserTransaction interface
In a session bean with bean-managed transactions, it is possible to mix JDBCand JTA transactions This practice is not recommended, however, because itcould make your code difficult to debug and maintain
If you’re unsure about how to set up transactions in an enterprise bean, here’s atip: In the deployment descriptor specify container-managed transactions Then,set the Required transaction attribute for the entire bean This approach willwork most of the time
Trang 3Figure 17 Options in Specifying Transactions
Transaction Timeouts
For container-managed transactions, you control the transaction timeout interval
by setting the value of the transaction.timeout property in the fig/default.propertiesfile For example, you would set the timeout value to
Bean-Managed Transaction Container-Managed Transaction
declare tx attributes in deployment descriptor
invoke Connection methods in bean
invoke UserTransaction methods in bean
Trang 4I SOLATION L EVELS 249
transaction.timeout=0
If the value is 0, the transaction will not time out
Only enterprise beans with container-managed transactions are affected by the
transaction.timeout property For enterprise beans with bean-managed, JTAtransactions, you invoke the setTransactionTimeout method of the User- Transaction interface
Isolation Levels
Transactions not only ensure the full completion (or rollback) of the statements
that they enclose, they also isolate the data modified by the statements The lation level describes the degree to which the data being updated is visible to
iso-other transactions
Suppose that a transaction in one program updates a customer’s phone number,but before the transaction commits another program reads the same phone num-ber Will the second program read the updated and uncommitted phone number
or will it read the old one? The answer depends on the isolation level of thetransaction If the transaction allows other programs to read uncommitted data,performance may improve because the other programs don’t have to wait untilthe transaction ends But there’s a tradeoff—if the transaction rolls back, anotherprogram might read the wrong data
You cannot modify the isolation level of a entity beans with container-managedpersistence These beans use the default isolation level of the DBMS, which isusuallyREAD_COMMITTED
For entity beans with bean-managed persistence and for all session beans, youcan set the isolation level programmatically with the API provided by the under-lying DBMS A DBMS, for example, might allow you to permit uncommittedreads by invoking thesetTransactionIsolation method:
Trang 5Updating Multiple Databases
The J2EE transaction manager controls all enterprise bean transactions exceptfor bean-managed JDBC transactions The J2EE transaction manager allows anenterprise bean to update multiple databases within a transaction The figuresthat follow show two scenarios for updating multiple databases in a single trans-action
In Figure 18, the client invokes a business method in Bean-A The businessmethod begins a transaction, updates Database-X, updates Database-Y, andinvokes a business method in Bean-B The second business method updatesDatabase-Z and returns control to the business method in Bean-A, which com-mits the transaction All three database updates occur in the same transaction
Figure 18 Updating Multiple Databases
In Figure 19, the client calls a business method in Bean-A, which begins a action and updates Database-X Then, Bean-A invokes a method in Bean-B,which resides in a remote J2EE server The method in Bean-B updates Database-
Trang 6U PDATING M ULTIPLE D ATABASES 251
Y The transaction managers of the J2EE servers ensure that both databases areupdated in the same transaction
Figure 19 Updating Multiple Databases Across J2EE Servers
Trang 8mecha-The J2EE platform defines declarative contracts between those who develop andassemble application components and those who configure applications in oper-ational environments In the context of application security, application provid-ers are required to declare the security requirements of their applications in away that they may be satisfied during application configuration The securityrequirements of an application are communicated in a declarative syntax in adocument called a deployment descriptor An application deployer employs con-tainer-specific tools to map application requirements captured in a deploymentdescriptor to security mechanisms that are implemented by J2EE containers TheJ2EE SDK provides this functionality with thedeploytool.
In many cases, J2EE containers can provide an application's security ity completely outside of the application implementation In other cases, theremust be a programmatic aspect to realizing an applications security functional-ity The declarative contract that accompanies an application must convey thesecurity requirements of the application, including identifying where it is neces-sary to bind implementation-embedded security functionality to environment-specific mechanisms or values
functional-J2EE security mechanisms combine the concepts of container hosting and thedeclarative specification of application security requirements with the availabil-ity of application-embedded mechanisms This provides a powerful model forsecure, portable, distributed component computing
Trang 9Authentication 254J2EE Users, Realms, and Groups 255Authentication Mechanisms 257Controlling Access to J2EE Resources 259Client Authentication 260
Web Client Authentication 261Application Client Authentication 261Setting Component Security Identities 262Container Authentication 262
Configuring EJB Target Security Requirements 263Configuring Resource Signon (Connectors) 264Authorization 264
Declaring Roles 265Declaring Method Permissions 265Declaring Role References 266Mapping Roles to J2EE Users and Groups 266Linking Role References to Roles 267Configuring J2SE Security Policy Files 267Determining the Caller Identity 267Making Portable Access Decisions Programmatically from Components267
Protecting Messages 268Application Scenarios 268J2EE Application Client 268Web Browser Client 268
Authentication
Authentication is the mechanism by which callers and service providers prove to
one another that they are acting on behalf of specific users or systems When the
proof is bidirectional, it is referred to as mutual authentication Authentication
establishes the call identities and proves that the participants are authenticinstances of these identities An entity that participates in a call without estab-
lishing or proving an identity (that is, anonymously), is called unauthenticated When calls are made from a client program being run by a user, the caller iden- tity is likely to be that of the user When the caller is an application component
acting as an intermediary in a call chain that originated with a user, the identity
may be associated with that of the user In this case, the component impersonates
the user Alternatively, one application component may call another with anidentity of its own and unrelated to that of its caller
Trang 10A UTHENTICATION 255
Authentication is carried out in two phases:
1 Service-independent authentication that requires knowledge of some
secret is performed to establish an authentication context that encapsulates the identity and is able to create proofs of identity, called authenticators.
2 The authentication context is then used to authenticate with other called orcalling entities
Controlling access to the authentication context, and thus the ability to cate as the associated identity, becomes the basis of authentication The follow-ing policies and mechanisms can be used for controlling access to anauthentication context:
authenti-• Once the user performs an initial authentication, all processes started bythe user inherit access to the authentication context
• When a component is authenticated, access to the authentication contextmay be available to other related or trusted components, such as those thatare part of the same application
• When a component is expected to impersonate its caller, the caller may delegate its authentication context to the called component.
J2EE Users, Realms, and Groups
A J2EE user is similar to an operating system user Typically, both types of usersrepresent people However, these two types of users are not the same The J2EEauthentication service has no knowledge of the user and password you providewhen you log on to the operating system The J2EE authentication service is notconnected to the security mechanism of the operating system The two securityservices manage users that belong to different realms
A realm is a collection of users that are controlled by the same authentication
policy The J2EE authentication service governs users in two realms: certificateand default
Certificates are used with the HTTPS protocol to authenticate web browser ents To verify the identity of a user in the certificate realm, the authenticationservice verifies a X509 certificate For step-by-step instructions, see Setting Up aServer Certificate (page 262) The common name field of the X509 certificate isused as the principal name
cli-In most cases, the J2EE authentication service verifies user identity by checkingthe default realm This realm is used for the authentication of all clients exceptfor web browser clients that use the HTTPS protocol and certificates
Trang 11A J2EE user of the default realm may belong to J2EE group (A user in the
cer-tificate realm may not.) A group is a category of users, classified by common
traits such as job title or customer profile For example, most customers of an commerce application might belong to theCUSTOMERgroup, but the big spenderswould belong to thePREFERREDgroup Categorizing users into groups makes iteasier to control the access of large numbers of users A later section,Authorization (page 264), discusses controlling user access to enterprise beans
e-Managing J2EE Users and Groups
The realmtool utility is a command-line program that ships with the J2EESDK You can use this utility to add to and remove users from the default andcertificate realms
To display all users in the default realm, type this command:
realmtool -list default
To add a user to the default realm, specify the-add flag The following mand adds a user named rover who is protected by the password red, andincludes rover in the customer and preferred groups:
com-realmtool -add rover red customer,preferred
To add a user to the certificate realm, you import a file containing the X509 tificate that identifies the user:
cer-realmtool -import certificate-file
To remove a user, you specify the-removeflag For example, to remove a usernamed tjones from the default realm, you would type the following command:
realmtool -remove default tjones
To add a group to the default realm, you specify the-addGroupflag The ing command adds the customer group:
follow-realmtool -addGroup customer
You cannot add a group to the certificate realm
To remove a group from the default realm, you specify the-removeGroup flag:
realmtool -removeGroup customer
Trang 12A UTHENTICATION 257Authentication Mechanisms
In a typical J2EE application, a user goes through a client container to interactwith enterprise resources in the web or EJB tiers Resources that are available tothe user may be protected or unprotected Protected resources are distinguished
by the presence of authorization rules, rules that restrict access to a subset of
non-anonymous identities To access a protected resource, a user needs topresent a non-anonymous credential so its identity can be evaluated against theresource authorization policy If a trust relationship between the client andresource containers does not exist, the credential must be accompanied by anauthenticator that confirms its validity This section describes authenticationmechanisms that the J2EE platform supports and explains how to usedeploy- tool to configure those mechanisms
Web-Tier Authentication
You can protect a collection of web resources (web components, HTML ments, image files, compressed archives, and so on) by specifying an authoriza-tion constraint (described in Controlling Access to Web Resources (page 259))for the collection If an anonymous user tries to access a protected web resource,the web container will prompt that user for a password to authenticate with theweb container The request will only be accepted by the web container after theuser identity has been proven to the web container and that identity has beenshown to be one of the identities granted permission to access the resource
docu-Caller authentication that is performed on the first access to a protected resource
is called lazy authentication.
When you try to access a protected web-tier resource, the web container vates the authentication mechanism that has been defined J2EE web containersare required to support HTTP basic authentication, form-based authentication,and HTTPS mutual authentication, and are encouraged, but are not required, tosupport HTTP digest authentication
acti-In basic authentication, the web server authenticates a principal using the user name and password obtained from the web client In digest authentication a web
client authenticates to a web server by sending the server a message digest alongwith its HTTP request message The digest is computed by employing a one-wayhash algorithm to a concatenation of the HTTP request message and the client’spassword The digest is typically much smaller than the HTTP request, anddoesn’t contain the password
Form-based authentication lets developers customize the authentication user
interface presented by an HTTP browser Like HTTP basic authentication,
Trang 13form-based authentication is not secure, since the content of the user dialog is sent asplain text, and the target server is not authenticated In single-signon environ-ments, discretion must be exercised in customizing an application’s authentica-tion interface It may be preferable to provide a single enterprise-wide customuser authentication interface, rather than implementing a set of application-spe-cific interfaces.
With mutual authentication, the client and server use X.509 certificates to
estab-lish their identity Mutual authentication occurs over a channel that is protected
by SSL Hybrid mechanisms that feature either HTTP basic authentication,form-based authentication, or HTTP digest authentication over SSL are also sup-ported
Configuring A Web Component’s Authentication Mechanism
To configure the authentication mechanism that a web component will use:
1 Select the web component in the tree view The Web Component inspectorwill be displayed
2 Select the Security tab
3 Choose one of the following authentication mechanisms from the UserAuthentication Method pulldown menu:
Using Hybrid Authentication to Enhance Confidentiality
Passwords are not protected for confidentiality with HTTP basic or form-basedauthentication To overcome this limitation, you can run these authenticationprotocols over an SSL-protected session and ensure that all message content,including client authenticators, are protected for confidentiality
To configure HTTP basic or form-based authentication over SSL:
1 Select the web component in the tree view The Web Component inspectorwill be displayed
Trang 14A UTHENTICATION 259
2 From the Security tabbed pane, make sure that Basic or Form Based havebeen selected in the User Authentication Method menu pulldown
3 Click on the Add button in the Security constraint section
4 Click on the Security constraint that was added
5 Select CONFIDENTIAL in the Network Security Requirement menu down
pull-Controlling Access to J2EE Resources
In a typical J2EE application, a client goes through its container to interact withenterprise resources in the web or EJB tiers Protected and unprotected resourcesmay be available to the user Protected resources are distinguished by the pres-ence of authorization rules that restrict access to some subset of non-anonymousidentities To access a protected resource, a user must present a non-anonymouscredential so its identity can be evaluated against the resource authorization pol-icy In other words, caller authentication is required any time a caller tries toaccess a protected component
Controlling Access to Web Resources
To control access to a web resource, you use the deploytool to specify a securityconstraint:
1 Select the web component in the tree view
2 Select the Security tabbed pane
3 Click the Add button in the Security Constraints section of the screen
4 Click the Edit button adjacent to the Web Resource Collection field to add
a web resource collection to the security constraint the web resource lection describes a URL pattern and HTTP method pair that refer to theresources that need to be protected
col-5 Click the Edit button adjacent to the Authorized Roles field to add anauthorization constraint to the security constraint You specify the set ofroles that can access the web resource collection
6 From the Transport Guarantee menu, select the user data constraint, eitherNone, Integral, or Confidential This setting indicates with what degree ofprotection the resource can be accessed
Controlling Access to Enterprise Beans
If you defined security roles for an enterprise bean, you can also specify themethods of the remote and home interface that each security role is allowed to
Trang 15invoke This is done in the form ofmethod-permission elements Ultimately, it isthe assignment of users to roles that determines if a resource is protected Whenthe roles required to access the enterprise bean are assigned only to authenticatedusers, the bean is protected.
Unprotected Resources
Many applications feature unprotected web-tier content, available to any callerwithout authentication Some applications also feature unprotected enterprisebeans In either tier, unprotected resources are characterized by the absence of arequirement that their caller be authenticated In the web tier, unrestricted access
is provided simply by leaving out an authentication rule In the EJB tier, stricted access is accomplished by mapping at least one role, which is permittedaccess to the resource, to the universal set of users independent of authentication
unre-Client Authentication
The J2EE authentication service controls access from all types of bean clients:J2EE application clients, stand-alone Java applications, and web components.When a J2EE application client starts running, its container pops open a windowthat requests the J2EE user name and password If you run the J2EE applicationclient described in Running the J2EE™ Application Client (page 58) you’ll seethis log-on window in action The authentication service verifies that the username and password from the log-on window exist in the default realm Afterauthentication, the user’s security context is associated with any call that the cli-ent makes to enterprise beans deployed in the J2EE server
Many applications do not require authentication For example, an online productcatalog would not force customers to log on if they are merely browsing Also,when you first start developing an application, you may find it convenient toallow an unauthenticated and anonymous user namedguestto access the appli-cation’s components
During deployment, you specify whether or not a web component is a protectedresource If the web component is unprotected, anyone may access it from theirbrowser If an unprotected web component accesses an enterprise bean, theauthentication service assigns it a certificate for theguestuser Any subsequentcalls to enterprise beans are associated with theguest user
Trang 16The J2EE platform does not specify mechanisms to support auto-registration.
Therefore, these mechanisms are specific to the container implementation
Web Client Authentication
This section will describe how to declare the web tier authentication nisms
mecha-Data Protection
TBD This section will describe how to use SSL to provide data protection Itwill talk about declaring data protection in the web tiers and explain the relation-ship between data protection and authentication
Developing a Custom Web Tier User Authentication Interface
TBD After briefly describing the form-based login authentication mechanism,this section will describe how to create a custom web-tier user authenticationinterface and explain how to install the interface
Application Client Authentication
TBD This section will describe the declarative aspects of application clientauthentication
This section will also explain how to configure a JAAS login module in an cation client
appli-Application client authentication to the web tier will be shown, but the sectionwill concentrate on application client authentication to the EJB tier
Trang 17Setting Component Security Identities
TBD This section will explain the configuration and declaration aspects of using
run-as-specified-identity andRunAs caller
Capturing a Security Context (Servlet)
TBD This section will describe how to set up a servlet security context for sequent EJB invocations This is done by using the session object, and recordingthe session id in the servlet, so that you can use it
sub-Container Authentication
TBD This section will describe how a container authenticates to its clients withthe J2EE SDK for a web server using SSL and an EJB server using CSIV2/SSL
Setting Up a Server Certificate
Certificates are used with the HTTPS protocol to authenticate web browser ents The HTTPS service of the J2EE server will not run unless a server certifi-cate has been installed To set up a J2EE server certificate, follow these steps:
cli-1 Generate a key pair and a self-signed certificate
Thekeytool utility enables you to create the certificate Thekeytoolity that ships with the J2EE SDK has the same syntax as the one that shipswith the Java 2™ Standard Edition However, the J2EE SDK version pro-grammatically adds a Java™ Cryptographic Extension provider that hasimplementations of RSA algorithms This provider enables you to importRSA signed certificates
util-To generate the certificate, run the keytool utility as follows, substituting
<certificate-alias> with the alias of your certificate:
keytool -genkey -keyalg RSA -alias <certificate-alias>
2 Thekeytool utility prompts you for the following information:
a keystore password - The default value of this password is changeit.You can change the password by editing theconfig/auth.properties
file
b first and last name - Enter the fully-qualified name of your server Thisfully-qualified name includes the host name and the domain name
c organizational unit - Enter the appropriate value
d organization - Enter the appropriate value