Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
BedrockMission!

Learn more

View all

Sign in to view all badges

SOLVED

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

jayv25585659
Level 6
Level 6
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
vanegi
Correct answer by
Employee
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
vanegi
Correct answer by
Employee
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