Hi, Gaurav Sharma here, I’m a developer with the Information Security Tools (IST) team. In today’s post I’ll concentrate on the topic of Impersonation in WCF.
1: class SampleService : ISampleContract
2: {
3: public void MyMethod( )
4: {
5: WindowsImpersonationContext impersonationContextObj = null;
6: impersonationContextObj = ServiceSecurityContext.Current.WindowsIdentity.Impersonate();
7: try
8: {
9: // Operation performed here will be under client's identity
10: }
11: finally
12: {
13: impersonationContextObj.Undo();
14: }
15: }
16: }
3: [OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
4: public void SampleServiceOperation( )
5: {
6: // if windows authentication is used then
7: // operations performed here will ne under
8: // client's identity
9: }
1: public enum TokenImpersonationLevel
3: None,
4: Anonymous,
5: Identification,
6: Impersonation,
7: Delegation
8: }
1: SampleContractClient serviceProxy = new SampleContractClient( );
2: serviceProxy.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Identification;
3: serviceProxy.SampleServiceOperation( );
4: serviceProxy.Close( );
5:
1: <client>
2: <endpoint behaviorConfiguration = "SampleImpersonationBehavior"
3: ...
4: />
5: </client>
6: <behaviors>
7: <endpointBehaviors>
8: <behavior name = "SampleImpersonationBehavior">
9: <clientCredentials>
10: <windows allowedImpersonationLevel = "Identification"/>
11: </clientCredentials>
12: </behavior>
13: </endpointBehaviors>
14: </behaviors>
15:
As a common design recommendation, the further from the client, the less significant its identity should be. In a layered architecture, each layer should run underneath its own identity, authenticate its direct callers, and implicitly trust its calling layer to authenticate its original callers.
Impersonation works directly opposite of this design guideline. Using impersonation also hinders scalability because several resources are allocated per identity. With impersonation, you will need as many resources as clients, and you will not be able to benefit from resource pooling mechanisms. Impersonation also makes resources administration complex. Also, if you rely on impersonation, it prohibits usage of non windows authentication mechanisms. If you do choose to use impersonation, use it carefully and only as a last resort when there is no other and better design approach.
Please feel free to email me with any questions you might have related to this topic. I’ll try to answer your queries to best of my knowledge. My email id is gauravsh@microsoft.com.
Happy Coding!
Gaurav Sharma (gauravsh@microsoft.com) Microsoft Information Security Tools (IST) Team Software Developer Engineer