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

Avatar

Avatar
Validate 25
Level 4
jayv25585659
Level 4

Likes

46 likes

Total Posts

131 posts

Correct reply

0 solutions
Top badges earned
Validate 25
Validate 10
Validate 1
Contributor 2
Ignite 5
View profile

Avatar
Validate 25
Level 4
jayv25585659
Level 4

Likes

46 likes

Total Posts

131 posts

Correct reply

0 solutions
Top badges earned
Validate 25
Validate 10
Validate 1
Contributor 2
Ignite 5
View profile
jayv25585659
Level 4

07-01-2020

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)

Avatar

Avatar
Give Back 5
Employee
vanegi
Employee

Likes

392 likes

Total Posts

378 posts

Correct reply

148 solutions
Top badges earned
Give Back 5
Give Back 3
Give Back 10
Give Back
Boost 50
View profile

Avatar
Give Back 5
Employee
vanegi
Employee

Likes

392 likes

Total Posts

378 posts

Correct reply

148 solutions
Top badges earned
Give Back 5
Give Back 3
Give Back 10
Give Back
Boost 50
View profile
vanegi
Employee

18-07-2020

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

 

Answers (0)