1
votes

I would like to capture information about the current user when publishing messages into rebus so that the handlers and sagas have transparent and correct access to the application user information. I'm getting a little lost in the source code but basically I'm trying to set up several things:

  1. A hook which runs when a message is published and puts the current user information into the header

  2. A hook which runs in the worker when the message is received and rewrites the ClaimsPrincipal.Current.

  3. A hook which runs in the worker when processing is done and resets ClaimsPrincipal.Current.

Any suggestions would be appreciated.

1

1 Answers

2
votes

You can use Rebus' events configurer to hook up the MessageSent event which is fired whenever an outgoing message is sent (i.e. send as well as publish and reply) like this:

 Configure.With(...)
     .(...)
     .Events(e => e.MessageSent += AutomaticallySetUsernameIfPossible)
     .(...)

and then your AutomaticallySetUsernameIfPossible might do something like this:

void AutomaticallySetUsernameIfPossible(IBus bus, string destination, object message)
{
    var principal = Thread.CurrentPrincipal;
    if (principal == null) return;

    var identity = principal.Identity;
    if (identity == null) return;

    var name = identity.Name;
    if (string.IsNullOrWhitespace(name)) return;

    bus.AttachHeader(message, Headers.UserName, name);    
}

in order to automatically transfer the currently authenticated user's name to all outgoing messages.

I suggest you use the built-in rebus-username header to transfer the username because it can be used by Rebus to establish the current principal on the receiving end by using the behavior configurer as decribed on the wiki page about user context