How do I access JAAS roles at arbitrary point in the code?

Joshua Fox picture Joshua Fox · Feb 9, 2009 · Viewed 7.1k times · Source

I want to access the full model of users with their roles in my SOAP app. For example, I might want to know the role of a user called "Fred."

How do I reach into some sort of global JAAS registry and do (pseudocode) globalRegistry.getUser("Fred").getPrincipals()? (Note that in JAAS, a role is represented by a Principal.)

I know how to get the Principal of the Subject from the LoginContext, but that has two problems.

  1. It is only at the moment of login, and I'd prefer not to code the aforementioned registry and store the Subject and Principal objects myself, as they are already stored by the appserver.
  2. Preferably, I want to be able to access this information even when Fred is not the current user.

I am using Jetty, but I presume that these behaviors are standard to JAAS.

Answer

Tom Anderson picture Tom Anderson · Jan 7, 2012

A pattern i have seen is:

AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
Set<Principal> principals = subject.getPrincipals();

Essentially, this finds the subject currently associated with the current thread, and asks for its principals.

One example of the use of this is in Apache Jackrabbit's RepositoryImpl. It's in the extendAuthentication method, whose job is to determine what Jackrabbit rights the current thread has when creating a new session (i think).

However, i should note that this may not necessarily actually work, at least in J2EE contexts. I'm using this code under JBoss AS7, and it doesn't find a subject. That might just be a bug, though.