Search code examples
javarestejbjaas

JAAS and web service authorization : get logged user


I've a JSF application that do login via JAAS. It works fine.

Now, my page calls a REST web service. I need to know who did the request.

In the request's header I have:

Cookie = JSESSIONID=XBHZuYnzgkGyQSR8kBLNSks_s7nuXAMli7Gp-9Mn.dlicitra; _ga=GA1.1.1590792307.1560863707

The web service is implemented in a Stateless EJB. The method is:

@Path(value = "myservice/{id}")
@GET
@Produces(value = "application/json")
public List<Records> getServices(
        @HeaderParam(value = "Cookie") String cookie,
        @PathParam(value = "id") Long id){
    return ... ;
}

How can I get the logged user from the cookie string?


Solution

  • As explained in the comment, instead of mangling with parsing or decoding the cookie's SessionId, I'd go with the Java EE's security API built-in solution of injecting the SecurityContext into the EJB, and getting the userPrincipal from it:

    @Context
    private SecurityContext securityContext;
    

    And in your method:

    Principal principal = securityContext.getUserPrincipal();
    

    See also:

    Baeldung's post on Java EE 8 Security API