Alternative to Thread.CurrentPrincipal in ASP.NET Web API

Those who know me also know that I was always an advocate of Thread.CurrentPrincipal (or ClaimsPrincipal.Current in .NET 4.5). But I also understand that some people (or frameworks) don’t like ambients and rather deal with instance variables.

To cater for that, I did a small addition to Thinktecture.IdentityModel – when you set the SetPrincipalOnRequestInstance property on AuthenticationConfiguration to true (which it is by default), the resulting ClaimsPrincipal gets added to the properties collection of the HttpRequestMessage instance.

You can then access it from anywhere where you have access to the request either directly or via a new extension method like this:

public ViewClaims Get()

{

    var principal = Request.GetClaimsPrincipal();

    return ViewClaims.GetAll(principal);

}

The code is on github and soon on nuget.

HTH

This entry was posted in ASP.NET, IdentityModel, WebAPI. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s