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:
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
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);
}
Комментариев нет:
Отправить комментарий