2

I have a stateless bean which has a method, where I want to get the current/logged user. My code to get it:

Principal p1 = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();

But I am getting nullpointer exception on this. Why is that?

Or is there any other way to get the logged user? I am using weblogic.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
victorio
  • 6,224
  • 24
  • 77
  • 113

2 Answers2

3

You're not supposed to grab the FacesContext in an EJB. Even more, your EJBs should be completely free from any JSF dependencies. In other words, you should not have any code imported from javax.faces.* package inside your EJBs. Your EJBs should be designed that way that they are reusable across all different front-ends you can think of such as JSF, JAX-RS, Struts, Spring-MVC and even "plain vanilla" Servlets.

If you're using container managed security or a security framework like Apache Shiro, then you're supposed to use the API-provided facilities for that. In case of "plain vanilla" container managed security (JAAS via web.xml and so on), you're supposed to obtain it form SessionContext (which is rightfully from javax.ejb package) which can be injected as @Resource.

@Resource
private SessionContext context;

public void doSomething() {
    Principal principal = context.getCallerPrincipal();
    // ...
}

An alternative would be to pass the JPA entity representation of the logged-in user as method argument.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I tried your code too, but I am getting the `` username. :/ – victorio Nov 04 '13 at 17:12
  • Are you using container managed security or a 3rd party API like Shiro? – BalusC Nov 04 '13 at 17:12
  • Wait, this appears to be a Weblogic specific issue: https://www.google.com/search?q=weblogic+sessioncontext+getcallerprincipal+anonymous Have you configured the `weblogic-ejb-jar` as shown in this blog? http://biemond.blogspot.com/2009/12/ejb-session-bean-security-in-weblogic.html – BalusC Nov 04 '13 at 17:14
-1

verify the import of the following library:

javax.faces.bean.SessionScoped;

Try again

Alexan
  • 8,165
  • 14
  • 74
  • 101