<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Owin &#8211; Cognim &#8211; Internet development</title>
	<atom:link href="https://www.cognim.co.uk/category/owin/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.cognim.co.uk</link>
	<description>Enterprise system implementation. Making the complex simple</description>
	<lastBuildDate>Mon, 11 Apr 2016 14:52:18 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
<site xmlns="com-wordpress:feed-additions:1">91553907</site>	<item>
		<title>Enhancing Claims with Owin Middleware &#038; Claims Transformation</title>
		<link>https://www.cognim.co.uk/transforming-claims-claimsprincipal/</link>
					<comments>https://www.cognim.co.uk/transforming-claims-claimsprincipal/#comments</comments>
		
		<dc:creator><![CDATA[Darren Hall]]></dc:creator>
		<pubDate>Mon, 11 Apr 2016 14:44:55 +0000</pubDate>
				<category><![CDATA[Authentication]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Owin]]></category>
		<category><![CDATA[ClaimsPrincipal]]></category>
		<guid isPermaLink="false">http://www.cognim.co.uk/?p=5385</guid>

					<description><![CDATA[Standardise your basic user data and add it to your ClaimsPrincipal for easy access! Recently I was working on a web api 2.0 project that used a bearer token for authentication and passed a UserId in the claims for the generated ClaimsPrincipal. Each controller in the project was accessing the User property from the ApiController [&#8230;]]]></description>
										<content:encoded><![CDATA[<h3>Standardise your basic user data and add it to your ClaimsPrincipal for easy access!</h3>
<p>Recently I was working on a web api 2.0 project that used a bearer token for authentication and passed a UserId in the claims for the generated ClaimsPrincipal.</p>
<p>Each controller in the project was accessing the User property from the ApiController base class to get the UserId from the claims and creating various other data to pass to a CQRS style query.  Some (simplified)  sample code follows;</p>
<pre class="lang:c# decode:true">var userId = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier);
var userRegion = GetUserRegionForUser(userId);
var userAccountName = GetUserAccountNameForUser(userId);
... Call an external query with userRegion and userAccountType to assemble data to return</pre>
<p>Doesn&#8217;t seem too bad, but this kind of code was littered throughout the project and in some cases only the UserId was passed to the external query which was then getting the other data itself.  Clearly we needed a unifying UserData class.</p>
<p>The UserData was only ever going to be three simple pieces of information (UserId, UserRegion and UserAccountName) and seemed like an ideal candidate for adding directly to the ClaimsPrinipal. You might think that a custom ClaimsPrincipal that inherits from a base class and adds UserData would be the way to go, but <a href="https://leastprivilege.com/2012/10/08/custom-claims-principals-in-net-4-5/" target="_blank">on his blog, Dominick Baier, suggests that deriviation is not ideal</a> and I tend to agree.</p>
<p>You could simply add the three pieces of information as separate claims and then read them back again in your controller:</p>
<pre class="lang:c# decode:true">var userId = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier);
var userRegion = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == "UserRegion");
var userAccountName = ((ClaimsPrincipal)User).Claims.SingleOrDefault(x =&gt; x.Type == "UserAccountName");</pre>
<p>but this approach is messy and doesn&#8217;t give us much more than the code we are trying to change.</p>
<h4>Using extensions</h4>
<p>The answer, as suggested in Dominick&#8217;s blog, relies on extension methods. Careful use of these allows us to not only get and set the UserData class on the principal but also to check for its existence.</p>
<pre class="lang:c# decode:true">public static class ClaimsPrincipalExtensions
{
  private const string UserRegion = "UserRegion";
  private const string UserAccountName = "UserAccountName";

  public static bool HasUserData(this ClaimsPrincipal principal)
  {
    return principal.HasClaim(claim =&gt; claim.Type == UserRegion);
  }

  public static UserData GetUserData(this ClaimsPrincipal principal)
  {
    var userId = principal.Claims.SingleOrDefault(x =&gt; x.Type == ClaimTypes.NameIdentifier)?.Value;
    var userRegion = principal.Claims.SingleOrDefault(x =&gt; x.Type == UserRegion)?.Value;
    var userAccountName = principal.Claims.SingleOrDefault(x =&gt; x.Type == UserAccountName)?.Value;

    return new UserData(userId, userRegion, userAccountName);
  }

  public static void AddSiteDetails(this ClaimsPrincipal principal, UserData userData)
  {
    principal.Identities.First().AddClaim(new Claim(ClaimTypes.NameIdentifier, siteAccessDetails.UserId));
    principal.Identities.First().AddClaim(new Claim(UserRegion, userData.UserRegion));
    principal.Identities.First().AddClaim(new Claim(UserAccountName, userData.UserAccountName));
  }
}</pre>
<h4>Getting the UserData</h4>
<p>Now we can access the UserData class from the principal with</p>
<pre class="lang:c# decode:true">var userData = ((ClaimsPrincipal)User).GetUserData();</pre>
<p>or, not relying on the ApiController base class</p>
<pre class="lang:c# decode:true ">var userData = ClaimsPrincipal.Current.GetUserData();</pre>
<h4>Creating the claims transformation</h4>
<p>But how do we add the claims in the first place, especially considering we are using Owin middleware? The easiest way is to use the freely available NuGet package <a href="https://www.nuget.org/packages/IdentityModel.Owin.ClaimsTransformation/" target="_blank">IdentityModel Owin ClaimsTransformation</a> <a href="https://github.com/identitymodel/owin.claimstransformation" target="_blank">(the simple source for which is available here if you want to hand craft it</a>).</p>
<p>Having installed this package, add a claims transformer class:</p>
<pre class="lang:c# decode:true ">public interface IClaimsTransformer
{
  Task&lt;ClaimsPrincipal&gt; TransformWithSiteDetails(ClaimsPrincipal principal);
}

public class ClaimsTransformer : IClaimsTransformer
{
  private readonly IUserDataProvider userDataProvider;

  public ClaimsTransformer(IUserDataProvider userDataProvider)
  {
    this.userDataProvider = userDataProvider;
  }

  public Task&lt;ClaimsPrincipal&gt; TransformWithUserData(ClaimsPrincipal principal)
  {
    if (principal.Identity.IsAuthenticated &amp;&amp; !principal.HasUserData())
    {
      principal.AddUserData(userDataProvider.GetDataByClaimsPrincipal(principal));
    }
    return Task.FromResult(principal);
  }
}</pre>
<p>Here I am passing in a UserDataProvider that can get me the user data from wherever it originates and using that to populate the principal.</p>
<h4>Integrating with Owin middleware</h4>
<p>Next add the transformer to your Startup.cs class (after your authentication middleware)</p>
<pre class="lang:c# decode:true">app.UseClaimsTransformation(incoming =&gt; Container.Resolve&lt;IClaimsTransformer&gt;().TransformWithUserData(incoming));</pre>
<p>Note that I am resolving the claimsTransformer from our IOC container, you can do it whichever way you choose.</p>
<p>And that&#8217;s it! Your authenticated controllers will now have the UserData contained in the ClaimsPrincipal and can easily be accessed or tested for.</p>
<p>I hope that helps.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.cognim.co.uk/transforming-claims-claimsprincipal/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5385</post-id>	</item>
	</channel>
</rss>
