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
- Call the method
- Verify that a user has a specific role (permission)
- Call the method
isCallerInRole(roleName)
- Call the method
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 { @Inject SecurityContext userContext; @Override 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(); resp.getOutputStream().println(String.format( "<html><body>" + "<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 userContext.isCallerInRole("admin"))); } }
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 |
Servlet | User name: HttpServletRequest.getUserPrincipal ()Returns In role: | @Inject
|
EJB | User name: EJBContext.getCallerPrincipal() If not logged in, returns a In role: | EJBContext or any of its subinterfaces can be injected in an EJB or retrieved via JNDI:
|
REST | User name:SecurityContext.getUserPrincipal() Returns In role: | @Context |
JSF | User name:ExternalContext.getUserPrincipal() Returns In role: | @Inject
|
CDI | User name:@Inject Principal principal; If not logged in, injects a In role: Not available | @Inject Principal principal; |
WebSocket | User name:Session.getUserPrincipal() Returns In role: Not available | Session is passed as an argument to handlers of WebSocket events |
XML Web Services | User name:WebServiceContext.getUserPrincipal() Returns In role: | WebServiceContext can be injected in a WS endpoint:
|
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.
Published on Java Code Geeks with permission by Ondrej Mihalyi, partner at our JCG program. See the original article here: Get logged-in user info in Jakarta EE – the simplest way Opinions expressed by Java Code Geeks contributors are their own. |