While working with OData controllers I came accross a challenge concerning authentication. The used authentication mode is Windows Authentication.
I wanted to invoke an OData controller through a service reference from another OData controller with the user of the original call. The user of the original call has to be impersonated because the controller encapsulated as a service reference checks, if the user has the required permissions. First I tried to call the service reference with the DefaultCredentials
of the CredentialCache
as described here but it didn’t work because on a standalone IIS server the call was done in the security context of the user IIS APPPOOL\DefaultAppPool
. I tried out several other options until I got the impersonation to work. The solution for getting the impersonation to work is shown below.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace how.To.Impersonate.Service.Reference.Call | |
{ | |
public static class CurrentUserDataHelper | |
{ | |
public static String GetCurrentUserId() | |
{ | |
var administrationService = GetServiceReferenceInstance(); | |
var identity = (WindowsIdentity)HttpContext.Current.User.Identity; | |
administrationService.Credentials = CredentialCache.DefaultCredentials; | |
using (var impersonationContext = identity.Impersonate()) | |
{ | |
return administrationService.CurrentUsers.ToList().First().Identity; | |
} | |
} | |
private static Contracts.CurrentUserData.Administration GetServiceReferenceInstance() | |
{ | |
return new Contracts.CurrentUserData.Administration(new Uri(ConfigurationManager.AppSettings["AKey"])); | |
} | |
} | |
} |
The GetCurrentUserId
method of the CurrentUserDataHelper
will be invoked from an ODataController. In this case the identity of the user can be retrieved from the HttpContext
. Then the DefaultCredentials
of the CredentialCache
have to be assigned to the service reference credentials property. To impersonate the call to the service reference the call has to be done inside the using statement that is responsible to impersonate the identity of the caller.
1 Comment »