Search code examples
wcfimpersonation

WCF service void method Will operation complete with Windows Impersonation


I have a WCF which is configured on Windows Authentication. This means that only authenticated Windows users will be able to access. I have a method which does not return anything but spins up a thread that does some long running task under the called windows user impersonation.

My code is below:

public void SampleTask();
{
    Task.Factory.StartNew(this.Activity);
}

private void Activity()
{
    WindowsIdentity identity = ServiceSecurityContext.Current.WindowsIdentity;
    using (WindowsImpersonationContext ctx = identity.Impersonate())
        {
        // Log status in a log database as "In Progress"
            // Do long running task (accessing database as current user)
        // retreive the results and save in a file
        // Update the log database as "Complete"
        }
}

My question is will the task still complete of retrieving the results and saving it and put the status as it should. Or will the impersonation will not work as there will be no open session. Or am I mistaken

Regards, Girija Shankar


Solution

  • The session should remain open as long as the method is executing. Even if the method is returning void, the request that started the execution of the method will be replied to.

    If you don't need a reply from the service, you can use the IsOneWay = true attribute on the method, which will tell the service to not send a reply to the client. Since this is a long-running method that is not returning data to the client, that makes it a good candidate for being a one-way method. In this case I'm not sure if the session would remain open or not, but it doesn't matter because the impersonation context will be scoped to the service, and have no dependency on the client.

    In your method, you can see this because of the declaration:

    WindowsIdentity identity = ServiceSecurityContext.Current.WindowsIdentity;
    

    The variable identity is scoped to the Activity method.

    using (WindowsImpersonationContect ctx = identity.Impersonate())
    

    The variable ctx is likewise scoped to the using block within the Activity method.

    The only time you would run into a problem that I can think of is if the service throws an exception and crashes - then of course the method wouldn't finish.

    To sum up, since the impersonation is based on the identity the service is running under, and you're not returning any data to the client, session should have no impact on both the method running to completion or the identity the service is running under.