Simon Miller Team : Web Development Tags : Web Development MVC

Stake Your Claim

Simon Miller Team : Web Development Tags : Web Development MVC

In my previous blog, I talked about the new OWIN implementation in .NET 4.5 and MVC5 which (among other things) provided a uniform way to authenticate a third party provider with your application. As an extension to this, and for authentication of a user in general, I wanted to see what was possible with Claims.

Claims allow you to store pieces of extra information about a user against their database table and their authenticated session. The identity model that is rolled for you in MVC5 gives you First Name and Last Name, but not much else. If you wanted to capture, say, a Date of Birth, you could customise the model used in the identity (and let code-first take care of changes to the database) or you could add a Claim to the user. This in effect adds a row to the AspNetUserClaims table (your naming may vary) that associates a claim with a user ID. .NET handily provides you with an assortment of standard Claim types as an enum, though you can roll your own if you wish.

Implementation is very simple. During your account creation method you may already be assigning a user to a Role. To create a Claim is just as simple:

Here I am assigning a string that represents the user’s date of birth with one of the pre-defined Claim Types. Other typical options include Email, MobilePhone, Locality, PostcalCode.

To access the claim data once a user has authenticated is just as simple. Here is an example of a helper method I created that extends the identity interface IIdentity to retrieve the stored Date of Birth claim:

And to call it from your view or controllers:

Simple!