DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Elevate your data management. Join a lively chat to learn how streaming data can improve real-time decision-making, and how to reduce costs.

Platform Engineering: Enhance the developer experience, establish secure environments, automate self-service tools, and streamline workflows

Build Cloud resilience. High-profiled cloud failures have shown us one thing – traditional approaches aren't enough. Join the discussion.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Related

  • Enhanced API Security: Fine-Grained Access Control Using OPA and Kong Gateway
  • Misconfiguration Madness: Thwarting Common Vulnerabilities in the Financial Sector
  • Using AWS WAF Efficiently to Secure Your CDN, Load Balancers, and API Servers
  • Building a Zero Trust API With ASP.NET Core: A Developer’s Guide

Trending

  • Lifecycle Microservices With GenAI Tools
  • How to Protect Yourself From the Inevitable GenAI Crash
  • Building Secure Smart Contracts: Best Practices and Common Vulnerabilities
  • Formatting Strings in Java: String.format() Method
  1. DZone
  2. Data Engineering
  3. Databases
  4. Get Logged-in User Info in Jakarta EE - The Simplest Way

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.

By 
Ondro Mihalyi user avatar
Ondro Mihalyi
·
Nov. 14, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
3.7K Views

Join the DZone community and get the full member experience.

Join For Free

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 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:

Specification API Methods to call How to retrieve the user context
Servlet User name: 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 EJB

In 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.

security API

Published at DZone with permission of Ondro Mihalyi, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enhanced API Security: Fine-Grained Access Control Using OPA and Kong Gateway
  • Misconfiguration Madness: Thwarting Common Vulnerabilities in the Financial Sector
  • Using AWS WAF Efficiently to Secure Your CDN, Load Balancers, and API Servers
  • Building a Zero Trust API With ASP.NET Core: A Developer’s Guide

Partner Resources


Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: