Retrieving the Subject executing a java.security.PrivilegedAction at runtime
I am trying to retrieve the Sub开发者_开发技巧ject that is currently executing a Privileged Action under the JAAS framework, in order to be able to extract its principals. Basically, I need to verify at run-time that the Privileged Action is indeed executed by the principal that has the right to do so.
Or, to put it differently: is it possible to get the current LoginContext at run-time as some kind of system property (and not by creating a new one)? This would easily allow extracting the Subject.
Are you sure you need the LoginContext?
If you just need the Subject (with all attached Principals), you can do
Subject activeSubject = Subject.getSubject(AccessController.getContext());
I think you need to manage such a mechanism yourself. For instance if this is a web application where you authenticate once and then associate the authentication with a session. You store the LoginContext
in the session. One trick to make it available in other parts of the code would be to make a thread local wrapper that you set/unset at the start/end of every thread invocation (such as a request).
public class LoginContextHolder {
private static ThreadLocal<LoginContext> ctx = new ThreadLocal<LoginContext>();
public static void set(LoginContext lc) {
ctx.set(lc);
}
public static LoginContext get() {
return ctx.get();
}
}
public class LoginContextFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
LoginContext ctx = null;
HttpSession sess = (HttpSession)((HttpRequest)request).getSession(false);
if (sess != null) {
ctx = (LoginContext)sess.getAttribute("ctx");
}
try {
LoginContextHolder.set(ctx);
chain.doFilter(request, response);
} finally {
LoginContextHolder.set(null);
}
}
}
精彩评论