wcfwcf-securitywcf-clientwalkthrough

WCF Client Impersonation


Can someone point me to a [relatively] simple walk-through on how to properly configure an ASP.Net hosted WCF 4.0 service to impersonate the credentials of a caller for just certain methods of the service, but allow anonymous access to other methods?

I've been reading a lot about this on MSDN, but the more I read, the more confused I get. Maybe I'm just a dunce, but this seems a lot harder than it should be :-(

I have looked through the posts here on SE, but none seem to point to an end-to-end sample or tutorial. There is a WCF guidance document on CodePlex, but it seems hopelessly out of date, and hasn't been updated since 2008.

Any help here would be GREATLY appreciated.


Solution

  • This can be done via the OperationBehaviorAttribute.Impersonation property

    [ServiceContract]
    interface ISelectiveImpersonationExample
    {
        [OperationContract]
        void ThisUsesImpersonation();
    
        [OperationContract]
        void ThisDoesNotUseImpersonation();
    }
    
    
    // Implementation
    class SelectiveImpersonationExampleImpl : ISelectiveImpersonationExample
    {
        [OperationBehavior(Impersonation=ImpersonationOption.Required)]
        public void ThisUsesImpersonation()
        {
            // ...
        }
    
        [OperationBehavior(Impersonation=ImpersonationOption.NotAllowed)]
        public void ThisDoesNotUseImpersonation()
        {
            // ...
        }
    }
    

    Make sure that you do not set the service's behavior's ImpersonateCallForAllOperations value to true. If you do, the ThisDoesNotUseImpersonation function will throw an InvalidOperationException.

    I'm going on theory here, and haven't actually done it in real life. If it doesn't work please let me know.