JSF - java method: getCurrentUserName

gaffcz picture gaffcz · Aug 27, 2012 · Viewed 11.8k times · Source

I'm able to pass the username from JSF to managed bean e.g. this way:

<script type="text/javascript" >
  function onLoad(){
    document.getElementById("form:user").value = "#{sessionScope['username']}";}
  window.onload = onLoad;
</script>

<h:inputHidden id="user" value="#{bean.username}"/>

Is it possible to get it directly using Java method? I've tried something like:

public String getCurrentUserName()
{
  String name = "";
  FacesContext facesContext = FacesContext.getCurrentInstance();
  ExternalContext externalContext = facesContext.getExternalContext();

  if (externalContext.getUserPrincipal() != null) {
    name = externalContext.getUserPrincipal().getName(); // null
  }
  return name;
}

or:

facesContext.getExternalContext().getRemoteUser();       // null
facesContext.getExternalContext().isUserInRole("pps");   // null

But user is always null.. what am doing wrong?

UPDATE (creation a session container):

public String login() {
  ...
  FacesContext context = FacesContext.getCurrentInstance();
  session = (HttpSession) context.getExternalContext().getSession(true);
  session.setAttribute("id", user.getId());
  session.setAttribute("username", user.getName());
  ...

Answer

BalusC picture BalusC · Aug 27, 2012
#{sessionScope['username']}

This basically prints the session attribute with the name "username". Something like the following in raw Java code (if you're familiar with the basic Servlet API):

response.getWriter().print(session.getAttribute("username"));

If this part works, then you are definitely not using container managed authentication at all and thus the container managed user principal and user role getters definitely won't return anything.

You can access a session attribute just the same way as you access a session scoped JSF managed bean (they are under the covers namely also stored as session attributes!):

@ManagedProperty("#{username}")
private String username; // +setter

or, of course, the clumsy way:

String username = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("username");

See also:


Unrelated to the concrete question: I highly doubt the usefulness of that hidden input field and that piece of JS. Why are you passing a variable which is already present in the server side back to the server side? Are you sure you really need to do it this way?