1

I am following this article to authenticate users of a Web API service I'm writing :

http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/

This works just fine.

In summary, we use a custom action filter (that gets applied to all requests), that checks an encrypted request header to determine who the user is.

However, I also have code in my controller action methods that needs to know who the current user is. Rather than repeat the logic that has been executed in the ActionFilter, is there a way I can set a variable in the action filter and refer to that in the controller action method?

I have also seen it suggested that MessageHandler should be used rather than an actionFilter. Would that help in some way?

Essentially I need to somehow flag up who the current user is in the Filter code and be able to refer to that in my controller

Or am I way off here? Is ther a smarter way? thanks

ChrisCa
  • 10,876
  • 22
  • 81
  • 118

3 Answers3

4

Create a Principal and store it in Thread.CurrentPrincipal.

You can then access it in the Web Api controller with User.Identity

This method works on my machine.

Community
  • 1
  • 1
Timothy Lee Russell
  • 3,719
  • 1
  • 35
  • 43
  • these links are also useful : http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/ and http://sixgun.co.uk/blog/2012/02/29/asp-net-web-api-basic-authentication/ – ChrisCa Aug 15 '12 at 11:51
3

The HttpRequestMessage object has a Properties collection where you can add arbitrary state that you can access in your controller action.

You would use the same approach if you used a HttpMessageHandler instead of an ActionFilter.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • Is there a more Security specific object that should be populated? Feels like there should be something already in the framework for this? - thanks for your help – ChrisCa Aug 14 '12 at 17:20
  • @ChrisCa The Thinktecture guys have built a bunch of security extensions to Web API and they decode the auth and create a Princial to store in Thread.CurrentPrincipal. See http://leastprivilege.com/2012/06/03/thinktecture-identitymodel-and-asp-net-web-api-the-messagehandler/ – Darrel Miller Aug 14 '12 at 18:26
2

Unfortunately there is no build in mechanism to support this kind of security.

In our project, we use a custom token in the Request.Headers collection which we round-trip in all Web Api calls. We created a custom ActionFilter that operates on all non-GET requests. We extract the token from the Request.Headers and compare it to the token in our IClaimsIdentity, which is accessible through Thread.CurrentPrincipal.Identity

Martin Devillers
  • 17,293
  • 5
  • 46
  • 88