2

I have some code in my AEM world that does a form ajax call to a restlet service. What I would like to know is what the code is to get the current logged in UserId? The page has session=false.

Does AEM have a cookie I can pull against? In the form I have a hidden field named cq_csrf_token but I did not see it matching up with anything from CRXDE.

If you know it would be cool to hear your input.

ogottwald
  • 113
  • 1
  • 3
  • 15

4 Answers4

3

Are you sure the user is logged in? You can obtain the currently logged in user from a Session object:

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

See also this Stackoverflow Post: https://stackoverflow.com/a/22549922/1377893

Community
  • 1
  • 1
mish
  • 1,055
  • 10
  • 29
2

If no user is logged-in, AEM would consider the user accessing the content as "anonymous" user.

Try this:

import javax.jcr.Session;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
...
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
Session session = resourceResolver.adaptTo(Session.class);
log.info("User="+session.getUserID());

or..

Authorizable auth = userManager.getAuthorizable(session.getUserID());
log.info("\n--- User,  
Principal="+auth.getID()+","+auth.getPrincipal().getName());

Should print the User name.. by-default if the user is not logged in, you will see "anonymous" as the user.

Suren Konathala
  • 3,497
  • 5
  • 43
  • 73
2

if you want to get user in java, you can user Resource Resolver API.

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

if you want to get user on Front end, you could use Profile Data Manager API

<script>
CQ_Analytics.ProfileDataMgr.data 
</script>

would give you information about current logged in user.

for your second question, request.getCookies() would give you all the cookies as a Cookie[]. Hope this helps

Shashi
  • 746
  • 10
  • 39
0

You can see the user id by putting the following code in a JSP.

<%@include file="/libs/foundation/global.jsp"%>
<%= resourceResolver.adaptTo(Session.class).getUserID() %>

BTW, the CSRF token is to protect the site from Cross-site request forgery attack.

Refer to this page for more details: https://docs.adobe.com/docs/en/aem/6-2/develop/security/csrf-protection.html