My Wiki

July 4, 2006

Accessing a secure EJB through a standalone java client

Filed under: EJB, JAAS — jaikiran @ 1:10 am

To access a secure resource(may be a EJB), from a standalone client, you need to do a JAAS login. Here’s an simple example which shows how to implement the same. But before going to the example, here’s the reason why we need to do a login. Consider a secured EJB “MyTestEJB”, deployed on a app server. The normal proceedure that you follow in a web-application to lookup the EJB and invoke a method on the same is as follows:

Context context = new InitialContext();
//lookup the home object
Object lookupObj = context.lookup(“MyTestEJBHomeJndiName”);
MyTestEJBHome home = (MyTestEJBHome) PortableRemoteObject.narrow(lookupObj, MyTestEJBHome.class);
//create the bean object from the home object
MyTestEJB myBean = home.create();
//invoke the method on the bean
myBean.someMethod();

In the steps above, when the method create is called on the home object, the app server internally checks whether the user who is doing this operation, is authenticated and authorised to do the same. If not, it will throw a SecurityException. The above statements will usually work in a web-application where usually you have a login page to carry out the login process.

Now, consider the case with a standalone java client which has just got a main method and which needs to invoke the secure bean. The application server will have no knowledge about which user is trying to do the operations on the bean(is he authenticated or authorised?). This is the reason why the standalone client needs to do a JAAS login, to let the application server know which user is trying to do the operation on the bean. Now lets look at the code for doing the same. Here we have a standalone java client with a main() method:

package myapp;

import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.Serializable;
import java.rmi.RemoteException;

/**
*
* Stand-alone client invoking a method on a secure EJB
*
*/
public class SomeStandAloneClient {

 /**
 * Default constructor
 *
 */
 public SomeStandAloneClient() {
 
 }
 
 /**
 * Main method
 *
 * @param args Command line arguments
 */
 public static void main(String[] args) {
 
  //obtain the username and password which are passed as part of command line arguments
  String userName = args[0];
  String password = args[1];
  
  System.out.println(“Logging in user: ” + userName);
  
  /*
  * The name of the file which will contain the login configurations
  */
  final String authFile = “someFilename.someExtension”;
  
  /*
  * Set the filename above, as part of system property, so that while doing a login,
  * this file will be used to check the login configurations
  */
  System.setProperty(“java.security.auth.login.config”, authFile);
  
  /*
  * During the login process(i.e. when the login() method on the LoginContext is called),
  * the control will be transferred to a CallbackHandler. The CallbackHandler will be
  * responsible for populating the Callback object with the username and password, which
  * will be later on used by the login process
  *
  * The “MyCallbackHandler” is your own class and you can give any name to it. MyCallbackHandler
  * expects the username and password to be passed through its constructor, but this is NOT
  * mandatory when you are writing your own callback handler.
  *
  *
  */
  MyCallbackHandler handler = new MyCallbackHandler(userName,password);
  
  try {
  
   /*
   * Create a login context. Here, as the first parameter, you will specify which
   * configuration(mentioned in the “authFile” above) will be used. Here we are specifying
   * “someXYZLogin” as the configuration to be used. Note: This has to match the configuration
   * specified in the someFilename.someExtension authFile above.
   * The login context expects a CallbackHandler as the second parameter. Here we are specifying
   * the instance of MyCallbackHandler created earlier. The “handle()” method of this handler
   * will be called during the login process.
   */
   LoginContext lc = new LoginContext(“someXYZLogin”,handler);
   
   /*
   * Do the login
   */
   lc.login();
   
   System.out.println(“Successfully logged in user: ” + userName);
  
  } catch (LoginException le) {
   System.out.println(“Login failed”);
   le.printStackTrace();
   return;
  }
  
  try{
  
   /*
   * Now that the user has logged in, invoke the method on the EJB
   */
   
   Context context = new InitialContext();
   
   //lookup the home object
   Object lookupObj = context.lookup(“MyTestEJBHomeJndiName”);
   MyTestEJBHome home = (MyTestEJBHome) PortableRemoteObject.narrow(lookupObj, MyTestEJBHome.class);
   
   //create the bean object from the home object
   MyTestEJB myBean = home.create();
   
   //invoke the method on the bean
   myBean.someMethod();
   
  } catch (RemoteException re) {
   System.out.println(“Remote exception: “);
   re.printStackTrace();
   return;
  } catch (NamingException ne) {
   System.out.println(“NamingException: “);
   ne.printStackTrace();
   return;
  } catch (CreateException ce) {
   System.out.println(“CreateException: “);
   ce.printStackTrace();
   return;
  }
  
 } //end of main()

} //end of SomeStandAloneClient

Now the CallbackHandler:

package myapp;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
*
* CallbackHandler which will be invoked by the login module during the login
* process of the client. This is a simple CallbackHandler which sets the username
* and password, which will be later used by the Login module for authorizing the
* subject. This class only handles NameCallback and PasswordCallback. It throws
* an UnsupportedCallbackException, if the Callback is other than the two mentioned
* above.
* The username and password are provided as input to this class through its constructor.
*
*
*/
public class MyCallbackHandler implements CallbackHandler {
 /**
 * Username which will be set in the NameCallback, when NameCallback is handled
 */
 private String username;
 
 /**
 * Password which will be set in the PasswordCallback, when PasswordCallback is handled
 */
 private String password;
 
 /**
 * Constructor
 * @param username The username
 * @param password The password
 */
 public MyCallbackHandler(String username, String password) {
 this.username = username;
 this.password = password;
 }
 
 /**
 * @param callbacks Instances of Callbacks
 * @throws IOException IOException
 * @throws UnsupportedCallbackException If Callback is other than NameCallback or PasswordCallback
 */
 public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
 
     for (int i = 0; i < callbacks.length; i++) {
         if (callbacks[i] instanceof NameCallback) {
             //if the Callback is for NameCallback, then set the name of the NameCallback to ‘userName’
             NameCallback nc = (NameCallback) callbacks[i];
             nc.setName(username);
            
         } else if (callbacks[i] instanceof PasswordCallback) {
             //if the Callback is for PasswordCallback, then set the name of the PasswordCallback to ‘password’
             PasswordCallback pc = (PasswordCallback) callbacks[i];
             pc.setPassword(password.toCharArray());
            
         } else {
             //if Callback is NOT NameCallback or PasswordCallback then throw UnsupportedCallbackException
             throw new UnsupportedCallbackException(callbacks[i], “Unrecognized Callback”);
         }
     }
 }
}
The file containing the login configuration(in our case “someFilename.someExtension”):
someXYZLogin{
org.jboss.security.ClientLoginModule required;
};

Remember, the someXYZLogin configuration name is the same that i provided to the constructor of the LoginContext. The contents of the above file let the LoginContext know, which class will be actually responsible for doing the login. In this case, since i am using jboss, we have specified “org.jboss.security.ClientLoginModule” as the class.Make sure that the login configuration file is under the same directory from where you will be running your client.

The command to run your client is the same that you would use to run a normal java class:

java SomeStandAloneClient someUsername somePassword

The someUsername and somePassword will be the arguments that you will pass to the main() method.

This is just a simple example. Internally, there are a lot of things, that go on as part of login. The following link has a great explanation about the same(JAAS related things are explained starting from the “An Introduction to JAAS” section in that article). I highly recommend, to go through it atleast once:

Article on Security

Create a free website or blog at WordPress.com.