Question

I am running an integration test with HttpClient and HttpServer (In-Memory).

When the test runs a token handler (message handler) is executed where I add this code just for a quick test:

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
        // other code removed for brevity...

    var principal1 = CreatePrincipal(1, "test");
    Thread.CurrentPrincipal = principal1;

    return await base.SendAsync(request, cancellationToken);
}

[Authorize]
[HttpGet]
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK, _service.Get(id));
}

When I debug into the action`s controller constructor I do base.User.Identity.IsAuthenticated and its set to TRUE.

I would have expected that the action is run because the Thread.CurrentPrincipal is set.

Why is it not working?

Was it helpful?

Solution

Thread.CurrentPrincipal is deprecated in Web API v2. Use HttpRequestMessage.GetRequestContext().Principal (both setting and getting)

OTHER TIPS

Whenever you set Thread.CurrentPrincipal, you should set HttpContext.User as well.

Hanselman has a blog post on the subject, and it's also covered in this SO answer. Also note that you may need to force an async yield, as described in this SO answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top