9

Get Logged-in User Info in Jakarta EE - The Simplest Way

 2 years ago
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.
neoserver,ios ssh client

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.

Nov. 14, 21 · Java Zone · Tutorial

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK