Search code examples
jakarta-eejmsjaasmessage-driven-bean

How do I access the Principal in a Message Driven Bean?


In the onMessage method of a MDB, how can I retrieve the name of the JAAS User Principal that initiated the request? My application is using Servlet login and a jdbcRealm.

I have considered adding this as a Message Property, but I would rather ensure that this is handled by JAAS.


Solution

  • It is handled inherently, all that you have to do is to inject and use MessageDrivenContext:

    ..
    @Resource
    private MessageDrivenContext mdc;
    
    public void onMessage(Message message) {
        Principal principal = mdc.getCallerPrincipal();
        System.out.println(principal.getName());
        //ALTERNATIVELY, YOU CAN USE A METHOD mdc.isCallerInRole("<role name>");
    }