Get User from SlingHttpServletRequest -> ResourceResolver -> Session in Servlet
Hi there community,
I am looking to get the current logged in user from the SlingHttpServletRequest. I am using a POST servlet that extends the SlingAllMethodsServlet.
I can confirm that the login-token cookie is being sent with the request:
String tokenCookie = TokenCookie.fromRequest(request).toString();
The tokenCookie string is populated with the correct login-token value. I have tried both GET and POST requests, and the cookie value is always correct. And, if I push that cookie into a browser and visit /crx/de I see the respective user logged in.
I have tried using the trusty resourceResolver adapted to a session to get the user:
final ResourceResolver resolver = request.getResourceResolver();
final Session session = resolver.adaptTo(Session.class);
final String username = session.getUserID();
This always returns anonymous
I have tried using the request attribute:
String userSessionName = (String)request.getAttribute("org.osgi.service.http.authentication.remote.user");
This always returns anonymous
I have tried using the request principal
Principal principal = request.getUserPrincipal();
String principalName = principal.getName();
This always returns anonymous
I did try using a service user session, as some have suggested, but as I expected that approach returns the service user rather than the actual request user.
What am I missing? I have been scratching my head all day on this issue, and I hope I am just missing something simple.
Thanks in advance