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.