6

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.

davidryan
  • 2,222
  • 20
  • 31
Fabio B.
  • 9,138
  • 25
  • 105
  • 177
  • Looks to be a duplicate, just found it http://stackoverflow.com/questions/1938517/how-to-get-sessioncontext-in-jboss but I see that anyone finding this question wouldn't of found the other one without knowing to look at JAAS first. – Andrew T Finnell May 13 '12 at 10:58

1 Answers1

11

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.

Andrew T Finnell
  • 13,417
  • 3
  • 33
  • 49
  • @FabioB. It doesn't have to be stateful. I'll update my Answer with another way of obtaining it. You should be able to use Injection with a Stateless bean, but if that doesnt' work you can look up the Context directly. – Andrew T Finnell May 13 '12 at 12:24