Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

What's the best way to get the currently logged in username (accessing publisher/dispatcher)

Avatar

Level 8
Session session = getRequest().getResourceResolver().adaptTo(Session.class);

UserManager userManager = getResource().adaptTo(UserManager.class);
Authorizable auth = userManager.getAuthorizable(session.getUserID());

userId = auth.getID();

 

So I have the code above to get the  currently logged in username in my local AEM instance. 

 

In my testing, session.getUserID() = auth.getID(). I feel that using session.getUserID() should be sufficient in trying to get the username of the currently logged in user.

 

In our stage and production environments, we have SSO setup and we're using Okta as our provider.

 

Is there anything I need to change in my code to make it better? Thanks

1 Accepted Solution

Avatar

Correct answer by
Employee

You can obtain the currently logged in user from a Session object:

Session session = resourceResolver.adaptTo(Session.class);
session.getUserID();

you can adapt your resource to UserManager class and get the current user or list down all the users and groups as per your requirement.

    Session session = resourceResolver.adaptTo(Session.class);
    UserManager userManager = resourceResolver.adaptTo(UserManager.class);
    /* to get the current user */
    Authorizable auth = userManager.getAuthorizable(session.getUserID());
    /* to get the property of the authorizable. Use relative path */
    Value[] names = auth.getProperty("./profile/familyName");
    /* to get the groups it is member of */
    Iterator<Group> groups = auth.memberOf(); 

 

View solution in original post

1 Reply

Avatar

Correct answer by
Employee

You can obtain the currently logged in user from a Session object:

Session session = resourceResolver.adaptTo(Session.class);
session.getUserID();

you can adapt your resource to UserManager class and get the current user or list down all the users and groups as per your requirement.

    Session session = resourceResolver.adaptTo(Session.class);
    UserManager userManager = resourceResolver.adaptTo(UserManager.class);
    /* to get the current user */
    Authorizable auth = userManager.getAuthorizable(session.getUserID());
    /* to get the property of the authorizable. Use relative path */
    Value[] names = auth.getProperty("./profile/familyName");
    /* to get the groups it is member of */
    Iterator<Group> groups = auth.memberOf();