views:

161

answers:

1

I have a WCF service that needs to know the Principal of the calling user.

In the constructor of the service I have:

Principal = OperationContext.Current.IncomingMessageHeaders.GetHeader<MyPrincipal>("myPrincipal", "ns");

and in the calling code I have something like:

        using (var factory = new ChannelFactory<IMyService>(localBinding, endpoint))
        {
            var proxy = factory.CreateChannel();
            using (var scope = new OperationContextScope((IContextChannel)proxy))
            {
                var customHeader = MessageHeader.CreateHeader("myPrincipal", "ns", Thread.CurrentPrincipal);
                OperationContext.Current.OutgoingMessageHeaders.Add(customHeader);

                newList = proxy.CreateList();
            }
        }

This all works fine.

My question is, how can I avoid having to wrap all proxy method calls in the using (var scope...{ [create header and add to OperationContext]?

Could I create a custom ChannelFactory that will handle adding the myPrincipal header to the operation context? Something like that would save a whole load of copy/paste which I'd rather not do but I'm not sure how to achieve it:)

Thanks

+2  A: 

The correct time to set a WCF principal is via IAuthorizationPolicy, by specifying a custom policy in configuration. This covered in full here. If you try setting the principal at other points (an inspector, perhaps) it can get reset by the system.

Marc Gravell