Monday, May 25, 2009

Getting User Credentials in GlassFish

Well, LDAP is great, we all know that. Others might consider other realms to authenticate-and-then-authorize. But one thing really bothered me when it is not very great in case I still need user's credentials to pass them elsewhere after realm has been passed. E.g. I want to execute some business objects for that specific user etc. More over, there is no standard JSR for it (and this just pisses me off). Of course, these credentials are unable to find in a regular servlet HTTP request, because we are not using basic authentication, like a putting credentials into an URL. So, here is a deal: an user logs into your system and after that your code wants to use the same credentials to get things from elsewhere, but you do not want (or can not) run SSO for some reasons — hence you have no service ticket to some certain enterprise segment.

How to get user's credentials then, without messing around with custom realms? In a GlassFish, the recipe is as follows:
  1. From GlassFish lib/ directory add appserv-rt.jar library to your class path in order to get all com.sun.enterprise.* become available in your application.

  2. Get a subject:
    import com.sun.enterprise.security.auth.login.PasswordCredential;
    import javax.security.auth.Subject;
    import javax.security.jacc.PolicyContext;
    import javax.security.jacc.PolicyContextException;

    ...

    Subject subject = null;
    try {
    subject = (Subject) PolicyContext
    .getContext("javax.security.auth.Subject.container");
    } catch (PolicyContextException ex) {
    ...
    }
  3. From the subject, get an iterator from private credentials object:
    Iterator iter = subject.getPrivateCredentials().iterator();
    while (iter.hasNext()) {
    PasswordCredential credential = (PasswordCredential) iter.next();
    ...
    }
  4. Now you can get PasswordCredential object that contains: a) realm name as getRealm(), b) user ID as getUser(), c) password as getPassword().
That's it.

2 comments:

tina said...

I am very grateful to you for your help.
You helped me solve a problem that had stalled for days.
Thanks so much!

tina said...

I am very grateful to you for your help.
You helped me solve a problem that had stalled for days.