

Get Logged-in User Info in Jakarta EE - The Simplest Way
source link: https://dzone.com/articles/get-logged-in-user-in-jakarta-ee-the-simplest-way-9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get Logged-in User Info in Jakarta EE - The Simplest Way
There are multiple ways to get info about the logged-in user in Jakarta EE but the Security API unifies them and makes it simple.
Join the DZone community and get the full member experience.
Join For FreeThe 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 a 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")));
}
}
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:
HttpServletRequest.getUserPrincipal
()Returns
null
if not logged in.In role:
HttpServletRequest.isUserInRole
()
@Inject
HttpServletRequest request;
HttpServletRequest
is also passed to servlet’s methods
EJB
User name: EJBContext.getCallerPrincipal()
If not logged in, returns a
Principal
with getName() == "ANONYMOUS"
instead of null
In role:
EJBContext.isCallerInRole()
EJBContext
or any of its subinterfaces can be injected in an EJB or retrieved via JNDI:@Resource
EJBContext ejbContext;
(EJBContext)new InitialContext()
.lookup("java:comp/EJBContext")
REST
User name:SecurityContext.getUserPrincipal()
Returns
null
if not logged in.In role:
SecurityContext.isUserInRole()
@Context
SecurityContext security;
JSF
User name:ExternalContext.getUserPrincipal()
Returns
null
if not logged in.In role:
ExternalContext.isUserInRole()
@Inject
ExternalContext externalContext;
FacesContext.getCurrentInstance()
.getExternalContext()
CDI
User name:@Inject Principal principal;
If not logged in, injects a
Principal
with getName() == "ANONYMOUS"
, similar to EJBIn role: Not available
@Inject Principal principal;
WebSocket
User name:Session.getUserPrincipal()
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:WebServiceContext.getUserPrincipal()
Returns
null
if not logged in.In role:
WebServiceContext.isUserInRole()
WebServiceContext
can be injected in a WS endpoint:@Resource
WebServiceContext wsContext;
The Security specification also provides a summary of all the available methods to retrieve the 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 rare that you will probably not use any of them ever.
Recommend
-
15
Create a Process as Logged-On-User from PowerShell Roger Zander ...
-
19
Logged in User Details In Azure AD App Service Idenifying the Logged-In User in Azure ADLately I have been experimenting with Azure AD and putting Apps behind Azure AD. Once they are behind Azure AD Auth...
-
12
Reporting on user’s last logged in date in Office 365 After a long, long wait, Microsoft is finally addressing one of the most common requests from Office 365/Microsoft 365/Azure AD admins – the ability to easily...
-
16
How to get all the users except current logged in user in Laravel 423 views 5 months ago Laravel While working in L...
-
7
Pankaj Bagul 21 minutes ago how to send logged-in user id from SAP BTP launchpad tile to SAP ABAP application 5...
-
5
ASP.NET Core: Three ways to refresh the claims of a logged-in user An ASP.NET Core application uses claims to hold the logged-in user’s
-
8
krishna sidda October 29, 2022 2 minute read
-
5
krishna sidda October 29, 2022 2 minute read
-
8
How can I find out the last time a user logged on from C++? ...
-
6
How to log out BTP user logged in SAP Build Apps? Skip to Content
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK