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



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

Accepted Solutions (1)

Accepted Solutions (1)




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

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

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(); 


Answers (0)