2

This is my backing bean (deployed to GlassFish):

@ManagedBean
@DeclareRoles({ "USER" })
@RolesAllowed("USER")
public class MyBean {
  public MyBean() {}
  public final String getId() {
    Principal p = .. // how and where?
    return p.getName();
  }
}

How and where I can get java.security.Principal object to understand who is logged in now?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
yegor256
  • 102,010
  • 123
  • 446
  • 597

1 Answers1

4

You can obtain it by ExternalContext#getUserPrincipal().

Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I am getting nullpointer exception on this code. why is that? – victorio Nov 04 '13 at 16:38
  • @victorio: all possible causes of an exception are usually already listed in exception's own javadoc: http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html Among others, when you attempt to call an instance method on a `null` reference. If you still stucks, just press "Ask Question" and post a good SSCCE. My best guess would be that you attempted to grab the `FacesContext` at the wrong moment (i.e. when it isn't been created yet), like in a servlet filter. – BalusC Nov 04 '13 at 16:39
  • thank you: http://stackoverflow.com/questions/19772780/why-does-my-facescontext-getcurrentinstance-getexternalcontext-getuserprinci – victorio Nov 04 '13 at 16:52