4

I'm running Glassfish 3.0 and I'm implementing JDBCRealm for login authentication. The username and roles are saved in a table called usertable. The authentication is working as expected.

But the problem is now when the user logs in, how can I retrieve the username of the logged in user in the application?

PS: I'm implementing JSF page and Managed Bean

fareed
  • 3,034
  • 6
  • 37
  • 65

3 Answers3

8

In JSF, you can retrieve the current Principal associated with the request and hence, the current session, using the ExternalContext object, which can be retrieved from the FacesContext. The Principal associated with the request is accessible from the ExternalContext using the getUserPrincipal() method:

FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();

The above invocation can be done in a JSF managed bean. You can invoke the getName() method on the Principal object to retrieve the name of the user as a String.

Note that, it possible for you to obtain a Principal instance that references the Anonymous user, if you are retrieving the Principal before authentication, or if the authentication scheme does not protect the entire site.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • 1
    `FacesContext.getExternalContext().getUserPrincipal();`? Shouldn't it be like `FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();`? Did that exist in some older versions of JSF at the time of this post? – Tiny Dec 11 '14 at 03:25
  • @Tiny, yes the `getCurrentInstance()` static method must be invoked first if you dont have the FacesContext instance. – Vineet Reynolds Dec 15 '14 at 08:01
3

Request.getRemoteUser or Request.getUserPrincipal, independent of the realm you use for authentication, so if you use a File realm for testing and a JDBC realm for production it will work in both cases. By the way, if you use JDBCRealm also have a look at FlexibleJDBCRealm.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • Does that FlexibleJDBCRealm exist in some version(s) of GlassFish now? It is mentioned at the end of that linked page, "*I have been in contact with SUN in the hope that FlexibleJdbcRealm (or something with similar flexibility) will be added to a future version of glassfish.*" – Tiny Dec 11 '14 at 03:39
  • @tiny Not that I'm aware of. But [the last message on the mailing list](http://wamblee.org/pipermail/flexiblejdbcrealm/2013-September/000056.html) says that the current version also works on GF4. – fvu Dec 11 '14 at 13:09
2

Your authenticate method should return a java.security.Principal which will contain the name.

http://download.oracle.com/javase/1.4.2/docs/api/java/security/Principal.html

Kal
  • 24,724
  • 7
  • 65
  • 65