14

I have configured a form based log in in my JSF 2.0 Application on GlassFish 3 server, using a custom Realm. What is the simpliest way of getting information about a logged in user, i.e. the users name.

Is this possible? Or is the current session just associated with a security role? If so, is there some way of making this possible without changing the log in configuration?

Simply put, what I want is to display a simple message like:

Logged in as username

on my webpages.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Tobbe Brolin
  • 455
  • 1
  • 3
  • 13

4 Answers4

21

The easiest way to get at the logged in user via EL (Expression Language) in JSF 2.0 would be:

#{request.remoteUser}

Tobbe's answer would work well to get at the remote user from within a backing bean.

Brian Leathem
  • 4,609
  • 1
  • 24
  • 44
19

The simple (maybe not the best) answer was:

FacesContext.getCurrentInstance().getExternalContext().getRemoteUser()

I'm shocked about how long it took me to figure that out.

alfonx
  • 6,936
  • 2
  • 49
  • 58
Tobbe Brolin
  • 455
  • 1
  • 3
  • 13
0

in your loginmanagedbean class define a currentUSer and in getter this: i didnt use an external logging in system and this works for me.

    public Login getCurrentUser() {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    if (externalContext.getUserPrincipal() == null){
        logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!current principal is null"); 
    }
    else{ 
        Integer id = Integer.parseInt(externalContext.getUserPrincipal().getName());
        logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!LOGGED USER "+ id); 
        try {
            currentUser = getLoginService().getLoginById(id);
        }
        catch (Exception ex) {
        } 
    } 
    return currentUser;
}
tolgayilmaz
  • 3,987
  • 2
  • 19
  • 19
  • What is this line? `Integer id = Integer.parseInt(externalContext.getUserPrincipal().getName());` You are trying to parse name as int? – Ajmal Salim Oct 21 '17 at 16:31
0

Inside Facelets you can use #{request.userPrincipal.name}.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177