Skip to main content
IBM  
Shop Support Downloads
IBM Home Products Consulting Industries News About IBM
IBM developerWorks : Java : Education - Tutorials
Java security, Part 2: Authentication and authorization
ZIPPDF (letter)PDF (A4)e-mail
Main menuSection menuFeedbackPreviousNext
4. Authorization in JAAS
  


Programmatic authorization example page 8 of 9


In this example, we see how programmatic authority decisions are coded. The PrivilegedAction class is called by a doAs method from the main JAASExample program, so the authenticated Subject is bound to the application context on the thread when it enters the run method.

We retrieve the current Subject from the access controller, and iterate through any contained authenticated Principals, looking for "joeuser". If we find him, we can do a sensitive operation and return. If not, we throw an AccessControlException. Obviously, in real life we would use a more administration-friendly and scalable technique rather than hard-coding user names directly into an application.


import java.io.*;
import java.security.*;
import javax.security.auth.*;
import javax.security.auth.login.*;
import java.util.*;
//
// This class is a sensitive Payroll function that demonstrates the
// use of programmatic authorization which only allows a subject 
// that contains the principal "joeuser" in class PayrollAction
implements PrivilegedAction {
     public Object run() {
       // Get the passed in subject from the DoAs
       AccessControlContext context = AccessController.getContext();
       Subject subject = Subject.getSubject( 
context );
       if (subject == null ) {
         throw new AccessControlException("Denied");
       }
       //
       // Iterate through the principal set looking for joeuser.  If
       // he is not found,
       Set principals = subject.getPrincipals();
       Iterator iterator = principals.iterator();
       while (iterator.hasNext()) {
         PrincipalImpl principal = (PrincipalImpl)iterator.next();
         if (principal.getName().equals( "joeuser" )) {
           System.out.println("joeuser has Payroll access\n");
           return new Integer(0);
         }
       }
       throw new AccessControlException("Denied");
     }
}

Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact