There're two places where you can set current principal in WEB API:
- Thread.CurrentPrincipal
- HttpContext.Current
In WEP API 1.0 you need to set them depending on the used host: in case of self-host, only Thread.CurrentPrincipal should be set, but in case of web hosting you need to set them both.
The common host independent approach of assigning current principal was this one:
Thread.CurrentPrincipal = principalToAssign;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principalToAssign;
}
But it has some flaws:
- Null cheking is a lack of abstraction
- In case of self-host scenario you have dependency from System.Web assembly
In WEB API 2.0 these flaws were eliminated. You should use HttpRequestContext class which has several implementations for different hosts. Every implementation provide its own logic of assigning current principal. You only need to set Principal property. For example, this is the implementation of Principal property of WebHostHttpRequestContext class used in web host:
public override IPrincipal Principal
{
get
{
return this._contextBase.User;
}
set
{
this._contextBase.User = value;
Thread.CurrentPrincipal = value;
}
}
So, in WEB API 2.0 you should authenticate your users in message handler as follows:
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.GetRequestContext().Principal = AuthenticateRequest(request);
return await base.SendAsync(request, cancellationToken);
}