JBoss AS 7 security: how to get currently logged username?
jakarta-ee, jboss, jboss7.x, security
Solution
You should be able to use JAAS. Which is what JBoss 7 ought to be using.
The calling principal will be stored in a `SessionContext` which you can obtain by telling JBoss it's a resource.
@Resource
private SessionContext context;
public void myAwesomeMethod() {
String currentUser = context.getCallerPrincipal().getName();
}
If for some reason the Injection doesn't work on a Stateless bean, you can look up the EJBContext direct.
@Stateless
public class HelloBean implements com.foo.ejb.HelloRemote {
public void hello() {
try {
InitialContext ic = new InitialContext();
SessionContext sctxLookup =
(SessionContext) ic.lookup("java:comp/EJBContext");
System.out.println("look up EJBContext by standard name: " + sctxLookup);
} catch (NamingException ex) {
throw new IllegalStateException(ex);
}
}
}
This snippet was obtained from 4 ways to obtain EJBContext.
Problem
I am in a Jboss AS 7 environment. My application's /admIn/* path is protected by a security-constraint which requires form based authentication. Security domain is database backed. It's ok but now I want to display a "good morning " in each page's header. I'm looking for some sort of getLoggedUsername() or getPrincipal() function but I can't find it. Please post a reference to the official docs if any. Thank you.