Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the logged-in user's username using JDBCRealm?

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

like image 511
fareed Avatar asked Dec 12 '22 11:12

fareed


2 Answers

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.

like image 157
Vineet Reynolds Avatar answered Dec 22 '22 00:12

Vineet Reynolds


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.

like image 25
fvu Avatar answered Dec 22 '22 00:12

fvu