ctron
ctron

Reputation: 534

Pre-authenticated user in Java EE/JBoss AS 6

I am migrating some Java EE modules from Spring to EJB and are now facing the problem that I need some sort of pre-authentication prior to calling a service method.

The problem is actually quite easy. A call comes in from an internal protocol handler (some thread started the proprietary protocol handler and received requests using a custom TCP protocol). Not this connection already authenticated the user and wants to call a service method next. This service method requires a principal information (user name) for processing.

So in Spring we simply pushed the SecurityContext to the local thread and removed it when the call was done.

Protocol Handler -> Set SecContext -> Call -> Remove SexContext -> End

Is there anything similar to that in Java EE/JBoss? I know there are "@RunAs" constructs but I don't know if they can be used programmatically. Or is there a way to "log in" using the JAAS LoginContext class? But how do I configure JAAS then?

Upvotes: 0

Views: 363

Answers (1)

Tom Anderson
Tom Anderson

Reputation: 47193

If this is purely a matter of getting an identity into the JAAS context, you should be able to do something like this:

final String username; // get this from somewhere
Princpal principal = new Principal() {
    public String getName() {
        return username;
    }
};
Subject subject = new Subject(true, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
Subject.doAs(subject, new PrivilegedAction<Void>() {
    public Void run() {
       // do your method call here
    }
});

Note that you can return a value from the PrivilegedAction by binding it to a type other than Void, and throw an exception by implementing PrivilegedExceptionAction instead.

Obviously if you have a more sophisticated idea of what a principal is, you could use that (implementing toString, hashCode, and equals would be a good idea).

Upvotes: 1

Related Questions