How to obtain logged in user name in JSF when using container managed authentication
Asked Answered
P

4

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.

Pawn answered 29/12, 2010 at 23:56 Comment(0)
C
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.

Carlicarlick answered 30/12, 2010 at 2:4 Comment(0)
P
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.

Pawn answered 30/12, 2010 at 0:58 Comment(0)
C
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;
}
Comparative answered 4/10, 2013 at 12:38 Comment(1)
What is this line? Integer id = Integer.parseInt(externalContext.getUserPrincipal().getName()); You are trying to parse name as int?Fluoroscope
T
0

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

Tragopan answered 12/6, 2014 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.