For basic authentication I have implemented a custom HttpMessageHandler based on the example shown in Darin Dimitrov's answer here: https://stackoverflow.com/a/11536349/270591
The code creates an instance principal of type GenericPrincipal with user name and roles and then sets this principal to the current principal of the thread:
Thread.CurrentPrincipal = principal;
Later in a ApiController method the principal can be read by accessing the controllers User property:
public class ValuesController : ApiController
{
public void Post(TestModel model)
{
var user = User; // this should be the principal set in the handler
//...
}
}
This seemed to work fine until I recently added a custom MediaTypeFormatter that uses the Task library like so:
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream,
HttpContent content, IFormatterLogger formatterLogger)
{
var task = Task.Factory.StartNew(() =>
{
// some formatting happens and finally a TestModel is returned,
// simulated here by just an empty model
return (object)new TestModel();
});
return task;
}
(I have this approach to start a task with Task.Factory.StartNew in ReadFromStreamAsync from some sample code. Is it wrong and maybe the only reason for the problem?)
Now, "sometimes" - and for me it appears to be random - the User principal in the controller method isn't the principal anymore I've set in the MessageHandler, i.e. user name, Authenticated flag and roles are all lost. The reason seems to be that the custom MediaTypeFormatter causes a change of the thread between MessageHandler and controller method. I've confirmed this by comparing the values of Thread.CurrentThread.ManagedThreadId in the MessageHandler and in the controller method. "Sometimes" they are different and then the principal is "lost".
I've looked now for an alternative to setting Thread.CurrentPrincipal to somehow transfer the principal safely from the custom MessageHandler to the controller method and in this blog post request properties are used:
request.Properties.Add(HttpPropertyKeys.UserPrincipalKey,
new GenericPrincipal(identity, new string[0]));
I wanted to test that but it seems that the HttpPropertyKeys class (which is in namespace System.Web.Http.Hosting) doesn't have a UserPrincipalKey property anymore in the recent WebApi versions (release candidate and final release from last week as well).
My question is: How can I change the last code snippet above so that is works with the current WebAPI version? Or generally: How can I set the user principal in a custom MessageHandler and access it reliably in a controller method?
Edit
It is mentioned here that "HttpPropertyKeys.UserPrincipalKey ... resolves to “MS_UserPrincipal”", so I tried to use:
request.Properties.Add("MS_UserPrincipal",
new GenericPrincipal(identity, new string[0]));
But it doesn't work as I expected: The ApiController.User property does not contain the principal added to the Properties collection above.