Get logged-in user info in Jakarta EE – the simplest way

The security before Java EE 8 / Jakarta EE 8 used to be a bit complicated and confusing. Every specification provided its own way to retrieve information about the logged-in user. The situation greatly improved with the introduction of the Security API that provides a unified way to do that – simply inject the SecurityContext CDI bean.

There’s still a small catch – this only works in the servlet context and EJB context. Or, in other words, when processing an HTTP request or inside any type of EJB. The good thing is that this covers most of the cases in which you’ll ever need to retrieve user information. In the other rare cases, you need to use one of the APIs which I also describe in this post.

Unified access to user info using Security API

With the Security API, retrieving information about the current user is pretty easy straightforward:

  • Inject SecurityContext
  • Get the name of the user
    • Call the method getCallerPrincipal()
    • If the result is null, no user is logged in
    • Otherwise, call the method getName() to get the name of the logged-in user
  • Verify that a user has a specific role (permission)
    • Call the method isCallerInRole(roleName)

Full example of a servlet that prints user’s name and whether the user is in role “admin”:

@WebServlet(urlPatterns = "/servlet")
public class UserInfoServlet extends HttpServlet {

    SecurityContext userContext;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // retrieve the principal and later check whether it's null or not
        Principal callerPrincipal = userContext.getCallerPrincipal();

                + "<p>User: %s</p>"
                + "<p>Is admin: %s</p>"
              + "</body></html>", 

        // print user's name only if the user is logger in and principal is not null
                callerPrincipal != null ? callerPrincipal.getName() : "not logged in",
        // true if user has admin role

Code language: Java (java)

Alternative ways to access user info

In case you can’t use the Security API, you can still use one of the other APIs that provide similar access to user information. A lot of other specification APIs provide similar methods to retrieve the name of the logged-in user and to check whether the user is in a specific role. Below is a summary of all possible ways:

Specification API
Methods to call
How to retrieve the user context
User name: HttpServletRequest.getUserPrincipal()

Returns null if not logged in.

In role: HttpServletRequest.isUserInRole()
HttpServletRequest request;

HttpServletRequest is also passed to servlet’s methods
User name: EJBContext.getCallerPrincipal()

If not logged in, returns a Principal with getName() == "ANONYMOUS" instead of null

In role:
EJBContext or any of its subinterfaces can be injected in an EJB or retrieved via JNDI:

EJBContext ejbContext;

(EJBContext)new InitialContext()
User name:

Returns null if not logged in.

In role:
SecurityContext security;
User name:

Returns null if not logged in.

In role:
ExternalContext externalContext;

User name:
@Inject Principal principal;

If not logged in, injects a Principal with getName() == "ANONYMOUS", similar to EJB

In role: Not available
@Inject Principal principal;
User name:

Returns null if not logged in.

In role: Not available
Session is passed as an argument to handlers of WebSocket events
XML Web Services
User name:

Returns null if not logged in.

In role:
WebServiceContext can be injected in a WS endpoint:

WebServiceContext wsContext;

The Security specification also provides a summary of all the available methods to retrieve user’s name and role information in 4.5. Relationship to Other Specifications.

What’s the best way?

I’d certainly recommend using only the Security API’s SecurityContext whenever possible, for the following reasons:

  • It’s a unified API so you can learn and remember a single way to access user information
  • It’s easy to use, just inject it as a CDI bean
  • It provides all the information provided by any of the other APIs
  • It’s cleaner in case the user isn’t logged – returns null Principal instead of a Principal with a default name

The only drawback is that currently it only works in Servlet and EJB contexts. Even though these 2 contexts are the most widely used, it’s still possible that in some rare cases the Security API can’t be used. Hopefully, the future versions of the Security specification will also cover other contexts. And even if not, the contexts where it wouldn’t work are related to some legacy and old Jakarta APIs and are nowadays very rarely used. In fact so rarely that you will probably not use any of them ever.

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha loading...