Tuesday, July 04, 2006

Accessing a secure EJB through a standalone java client

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 final 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) {
NameCallback nc = (NameCallback)callbacks[i];
nc.setName(username);
} else if(callbacks[i] instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback)callbacks[i];
pc.setPassword(password.toCharArray());
} else {
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.

Please 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

13 comments:

Anonymous said...

Thanks a lot, I have looking for a example or something for connect a client with an aplication in jboss with jaas and I find the answer here. It works!!

Jaikiran said...

Glad to know it helped you.

-Jaikiran

Anonymous said...

Thank U very mcuh.. I've been looking so much how to work with JMS, and casually I found also the standalone and jboss comunication, stuff that also needed. Thx :)

Jaikiran said...

Glad again :)

ChangeMyLife said...

When I package my bean, i enclose file "ejb-jar.xml" inside META-INF. So, I must place two file "jboss.xml" and "login-config.xml" ?(where ?).
Help me ! (Sorry, my E is not good.)

Jaikiran said...

JBoss already comes with a login-config.xml. You will find it in %JBOSS_HOME%/server/default/conf folder. Just add/edit contents in that file for the loginmodules. As far as the ejb jar file is concerned, you can package the ejb-jar.xml and jboss.xml in the jar file.

Abhinav Nigam said...

Nice Informative posts Jai.

Please see my post on javaranch here. I will be happy if you can suggest something. I have been stuck with this problem for a while now.

Jagadeesh HS said...

This works when i write this EJB Client on same machine where my EJB Deployed Jboss is running.


But how will this CLient know where is my EJB Deployed when i am running on some other server.

Jaikiran said...

Jagadeesh,

If the client wants to lookup a bean deployed on the remote server then you can pass the remote server details in the InitialContext as follows:


//JBoss specific parameters passed through Properties
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.PROVIDER_URL, "jnp://remoteMachineIPAddress:1099");
p.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
Context context=new InitialContext(p);

context.lookup(".....");

Anonymous said...

I have an standalone application that connect to a Jboss server to request EJB methods.
I want to secure the request to the EJB methods and provide an swing form that ask an username and password to the user.
Where i put the authentication aspect, in the client or the server or both?

Jaikiran said...

You need not put the authentication on the client side. You can just pass on the credentials to the server and the server will do a JAAS authentication on server side.

Section 8.4.1. How the JaasSecurityManager Uses JAAS at Security in JBoss has explained this specific scenario.

Anonymous said...

thx men, you made my day.

Unknown said...

As the client side login module not authenticating the user actually.It simply sending the credential to the jboss (as much as I have understood). Actual authentication is being made when ejb call is made. My question is - how does the jboss come to know about the credential when actual athentication is being made?

Thanks in advance.