Appending username using headers

Component: NServiceBus
NuGet Package NServiceBus (7.x)

This sample demonstrates how to append the current username to outgoing messages and then how to extract that value when messages are handled.

Fake principal

For demonstration purposes, prior to sending a message, the Thread.CurrentPrincipal will be replaced with a new instance. In a production scenario, the Thread.CurrentPrincipal would be either the impersonated user from IIS or the current user sending a message.

var identity = new GenericIdentity("FakeUser");
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
var message = new MyMessage();
await endpointInstance.Send("Samples.UsernameHeader.Endpoint2", message)
    .ConfigureAwait(false);

Custom header with a mutator

The recommended approach for capturing the current user is to create a transport mutator that extracts the current identity and then adds it to the header of every outgoing message.

Outgoing mutator

The outgoing mutator extracts Thread.CurrentPrincipal.Identity.Name and appends it to a message header.

public class UsernameMutator :
    IMutateOutgoingTransportMessages
{
    static ILog log = LogManager.GetLogger("Handler");

    public Task MutateOutgoing(MutateOutgoingTransportMessageContext context)
    {
        log.Info("Adding Thread.CurrentPrincipal user to headers");
        context.OutgoingHeaders["UserName"] = Thread.CurrentPrincipal.Identity.Name;
        return Task.CompletedTask;
    }
}

Register the Mutator

endpointConfiguration.RegisterComponents(
    registration: components =>
    {
        components.ConfigureComponent<UsernameMutator>(DependencyLifecycle.InstancePerCall);
    });

The Handler

From within a handler (or saga) this value can be used as follows:

public class HandlerUsingCustomHeader :
    IHandleMessages<MyMessage>
{
    static ILog log = LogManager.GetLogger("HandlerUsingCustomHeader");

    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        var headers = context.MessageHeaders;
        var usernameFromHeader = headers["UserName"];
        log.Info($"Username extracted from header: {usernameFromHeader}");
        return Task.CompletedTask;
    }
}

Related Articles


Last modified