29.01.2013 Views

WebSphere Application Server - IBM Redbooks

WebSphere Application Server - IBM Redbooks

WebSphere Application Server - IBM Redbooks

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

► java.security.Principal getUserPrincipal()<br />

The getUserPrincipal method allows the developer to get the name of the<br />

current caller. To do this, you need to call getName() on the<br />

java.security.Principal object returned.<br />

Principal principal=request.getUserPrincipal();<br />

String username=principal.getName();<br />

Important: getRemoteUser() and getUserPrincipal() return null as a result,<br />

even if the user is logged in, unless the servlet or the JSP itself is secured.<br />

If you opt to program J2EE calls into your application, you need to do the<br />

following:<br />

1. Define users and groups to the Express <strong>Application</strong> <strong>Server</strong> operating system.<br />

2. Define roles for the application in the Web module deployment descriptor.<br />

3. Define constraints (optional).<br />

4. Assign users or groups to roles in the Web module deployment descriptor.<br />

5. Define the authentication method.<br />

6. Code the servlets to retrieve and check the user role.<br />

7. Enable global security on the Express <strong>Application</strong> <strong>Server</strong>.<br />

Note that the first four steps are the same as those needed to implement<br />

declarative security. The difference is that you do not need to enable <strong>WebSphere</strong><br />

global security and you must add code into your application to provide<br />

authorization.<br />

Sample usage of security methods<br />

Example 16-2 shows a sample of implementing programmatic security. In the<br />

following code the servlet checks to see if the principal attempting to execute the<br />

code is in the proper role before allowing the code to be executed.<br />

Example 16-2 Sample code using the servlet security methods<br />

// getting the environment variables for restricted role<br />

// and for maximum transferable amount<br />

restrictedRole=(String)environment.lookup("RestrictedRole");<br />

maxWebTransferAmount=(Integer)environment.lookup("MaximumWebTransferAmount");<br />

// checking if the user is restricted to a certain amount of transfer<br />

if(request.isUserInRole(restrictedRole) &&<br />

transferAmount>maxWebTransferAmount.intValue()) {<br />

// create an error message<br />

// the user cannot transfer the requested amount<br />

// forward the request to the response page with the message<br />

Chapter 16. Security 569

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!