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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With