Click here to Skip to main content
15,891,513 members
Articles / Security
Tip/Trick

Claim Based Security .net

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
11 Jan 2015CPOL2 min read 14.6K   8  

Introduction

In the old world of web applications every application had it's own way of authenticating users. User presenting the identifier and the credentials to an application and the application establishing an identity to the user. Based on the credentials presented, if the application is able to authenticate that the user is what he is claiming to be, the identity becomes an authenticated identity. The user is authorized to have access to resources, based on the roles of which the user is part. With the burst in web applications it was not a viable solution to keep on creating users for different applications so we started using someone else's authentication (like Google authentication, or Facebook).

In this model a user presented a Claim to an application not credentials. For example my User Claim would be

Name: Himanshu Arora

Email address: abc@abc.com

Role: Developer

For a claim to be of any practical value, it must come from an entity the application trusts. Like when other use google or facebook credentials they trust that claim shared by google is a correct one. This kind of applications which goes on other application for Trust is known as Relying Party (RP). The entity that the RP application relies on is called the Issuing Authority.

 

Using the code

To perform claim based authetication in .net 4.5 we need following actions:

1. Create a sample Claim and Principal Class.

C++
// Setting Claim and ClaimPrincipal
 var claims = new List<Claim>()
            {
            new Claim(ClaimTypes.Name, "Himanshu Arora"),
            new Claim(ClaimTypes.Email, "abc@abc.com"),
            new Claim(ClaimTypes.Role, "Developer"),
            };
            var id = new ClaimsIdentity(claims, "Test");
            var principal = new ClaimsPrincipal(new[] { id });
            Thread.CurrentPrincipal = principal;

 

Claim Class represent the Claim Presented by an Entity.

ClaimTypes:  Constants for the well-known claim types that can be assigned to a subject.

ClaimsIdentity: Represents a claims-based identity.

ClaimsPrincipal: Support Multiple Claim based identity

In above code snippet we have created a sample Claim identity object, but in real world that object would be given by Issuing Autority. We are creating ClaimsPrincipal object from identity and assign that Pricipal to CurrentPrincipal of current thread.

2. Calling Method where Authorization is required

C++
// Calling sample mathod where we want to check Authorisation.
  [ClaimsPrincipalPermission(SecurityAction.Demand, Operation = "ValidateMe", Resource =
        "Roles")]
        private static void ValidateMe()
        {
            Console.WriteLine("You are authorised to call this method.");
        }

For the Method where we need to perform authorization, we need to decorate it with ClaimsPricipalPermission as shown in the snapshot above.

3. Adding AuthorizationManager which will validate claims for different Methods, as shown in code snippet below.

C++
// Calling sample mathod where we want to check Authorisation.
   public class AuthorizationManager : ClaimsAuthorizationManager
    {
        public override bool CheckAccess(AuthorizationContext context)
        {
            string resource = context.Resource.First().Value;
            string action = context.Action.First().Value;
            if (action == "ValidateMe" && resource == "Roles")
            {
                ClaimsIdentity id = (context.Principal.Identity as ClaimsIdentity);
                if (id.Claims.Any(c => c.Type == ClaimTypes.Role &&
                c.Value.Equals("Developer")))
                        return true;
            }
            return false;
        }
    }

 

4. Now some configs.

C++
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="system.identityModel"
    type="System.IdentityModel.Configuration.SystemIdentityModelSection,
System.IdentityModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089"/>
  </configSections>
  <system.identityModel>
    <identityConfiguration>
      <claimsAuthorizationManager
      type="ClaimsBasedIdentityConsoleApp.AuthorizationManager,
ClaimsBasedIdentityConsoleApp"/>
    </identityConfiguration>
  </system.identityModel>
</configuration>

 

Conclusion

In the code above we have seen that we can easily use Claim based security with .net applications. Above code uses .net framework 4.5.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --