aspnet / AspNetWebStack

ASP.NET MVC 5.x, Web API 2.x, and Web Pages 3.x (not ASP.NET Core)
Other
858 stars 354 forks source link

Premature disposal of WindowsIdentity in async controller method #255

Closed avivanoff closed 3 years ago

avivanoff commented 5 years ago

I have a Web API that uses Integrated Windows authentication and the following controller:

[Authorize]
[RoutePrefix("identity")]
public sealed class IdentityController : ApiController
{
    [HttpGet]
    [Route("1")]
    public async Task<String> GetIdentity1Async(CancellationToken cancellationToken)
    {
        var identity = (WindowsIdentity)this.User.Identity;
        using (identity.Impersonate())
        {
            await Task.Delay(1, cancellationToken)
                      .ConfigureAwait(true);
        }

        return identity.Name;
    }

    [HttpGet]
    [Route("2")]
    public async Task<String> GetIdentity2Async(CancellationToken cancellationToken)
    {
        await Task.Delay(1, cancellationToken)
                  .ConfigureAwait(true);

        var identity = (WindowsIdentity)this.User.Identity;
        using (identity.Impersonate())
        {
            await Task.Delay(1, cancellationToken)
                      .ConfigureAwait(true);
        }

        return identity.Name;
    }
}

Why does GetAsync1Method works, while GetAsync2Method throws

System.ObjectDisposedException: 'Safe handle has been closed'

on return statement?

mkArtakMSFT commented 3 years ago

Hi. It looks like this is a question about how to use ASP.NET. While we do our best to look through all the issues filed here, we are not a general-purpose forum. To get a faster response we suggest posting your questions to StackOverflow.