Thursday, April 3, 2014

Designing claims-based tokens using Security Assertion Markup Language(SAML)

The Security Assertion Markup Language (SAML) specification is an open security standard envisioned by Organization for the Advancement of Structured Information Standards (OASIS) Technical Committee for the exchange of security context across service boundaries. The SAML tokens are XML-based (can be transmitted using SOAP/HTTP) and provide a way of implementing claims-based identity that is particularly useful in interoperable scenarios across the identity providers and the service providers.

Following example shows how to create the SAML security tokens using the System.IdentityModel assembly in .NET Framework 4.0.

    Create a new Visual C# Console Application project in Visual Studio
  1. Create a new Visual C# Console Application project in Visual Studio
  2. Add a reference to System.IdentityModel and System.ServiceModel assembly
  3. Open the Program.cs file, and include the System.IdentityModel.Claims, System.IdentityModel.Tokens, System.ServiceModel   and the System.Security.Principal namespaces.
  4. Before we can create SamlSecurityToken, we need to create an instance of the SamlAssertion object that holds the claims information abstracted from the current windows identity. We will write a private static method that accepts a collection of the Claim objects and returns a SamlAssertion object.


  5. Note that SAML v1.1 specification puts a restriction that only resources identifiable by a named string can be used as a SamlAttribute value. In our example, we are using a helper method to translate SecurityIdentifier into readable NTAccount named permissions:


  6. Now, In main method create instance of SamlSecurityToken using the SamlAssertion instance returned from the method “CreateSamlAssertionFromWindowsIdentityClaims()”.


  7. Now Run the program and put debugger on token generation line to see the token.


Tuesday, March 25, 2014

Claims Based Identity Model

Claims based security is based on the concept that the identity of a person can be represented by a set of claims about that person. A claim is a bit of information that describes the person in a way that is digitally useful. Claims typically contain the usual user name, or email, but they can include much more. Information such as roles, phone numbers, zip codes, addresses, anything that is typically used by applications to customize the user experience.
Claims-based identity provides a standard way of acquiring identity information by heterogeneous applications to validate service requests within and outside an organization and also over the Web.

Abstracting Identity with Claims:
Authentication and authorization are two of the most common aspects of the application security. In Windows, security is generally handled using the Kerberos or the NTLM security tokens.
This works well within the boundaries of the Windows ecosystem; however, it gets difficult if the application has to support the users that do not have Windows Active Directory credentials. In the real world, the applications spanning multiple platforms interact with each other and require the security context to be shared. Using a claims-based identity model provides a robust way of handling authentication and authorization across the discrete systems.

Claims Base Authentication:
Claims-Based architecture allows you to delegate authentication logic into another entity. This entity is a “some” layer which abstracts all authentication related coding and gives your application what it needs: is the user authenticated or not, and some information about the user (called claims or assertions) that lets your application take authorization decisions.
How to do it…
Following example demonstrate how you can create a collection of claims from a WindowsIdentity object,

1.    Create a new Visual C# Console Application project in Visual Studio



2.       Add a reference to System.IdentityModel assembly

3.       Open the Program.cs file, and include the System.IdentityModel.Claims and the System.Security.Principal namespaces.

4.       In the Main method, create a new instance of the WindowsClaimSet class, and pass the current context identity as a parameter to the constructor. And then Loop through the ClaimSet object and print the claim information into the console output



5.       Compile and run the project. The result is displayed in the console window:


How it works…

The WindowsClaimSet class inherits from the System.IdentityModel.Claims.ClaimSet. ClaimSet represents a collection of claims (System.IdentityModel.Claims.Claim) associated with an entity. The WindowsClaimSet constructor accepts the current Windows user identity as a parameter and returns a ClaimSet object containing the collection of claims that represent the Windows Active Directory groups of the user. The current Windows user identity is fetched using the WindowsIdentity.GetCurrent method. Generated ClaimSet can be used to create a signed security token that can be passed on to a service to create a security context and implement role-based access control.

A claim is used to identify a user or provide access to a particular resource requested by the user. There are three properties exposed by the Claim class:

ClaimType: It identifies the type of claim. In our example, Sid (security identifier) and Name are the two claim types displayed in the console window.

               Resource: It identifies the resource associated with the claim.

Right: It is a URI representing the Identity or PossessProperty right associated with the claim. PossessProperty determines whether the user has the access to Resource.

Both the Claim and the ClaimSet classes are serialization-friendly, which allows them to be transmitted over service boundaries.

Tuesday, March 11, 2014

A Brief Introduction to the Web API

Web API provides a simple yet powerful framework for building
REST-based services that can be consume by a broad range of clients including browsers, mobiles, iphone and tablets.

With WebAPI content negotiation, we can return data based on the client requests. What I mean is, if the client is requesting the data to be returned as JSON or XML, the WebAPI framework deals with the request type and returns the data appropriately based on the media type. By default WebAPI provides JSON and XML based responses.

Let’s look at just a few of these new features:
  • Convention-based CRUD Actions:
    HTTP 
     actions (e.g., GET and POST) are automatically mapped to controller methods(also known as controller actions) by their names. For example,on a controller called Products, a GET request such as/api/products will automatically invoke a method named “Get”on the controller. Further, the Web API automatically matches the number of arguments given in the URL to an appropriate controller method. Therefore, the URL /api/products/32 would automatically invoke the Get(long id) method. The same magic also applies to POST, PUT, and DELETE calls.
  • Built-in Content Negotiation: In MVC,  controller methods that return JSON or XML have to be hard-coded to specifically return one of those content types. But with the Web API, the controller method need only return the raw data value, and this value will be automatically converted to JSON or XML, per the caller’s request.The caller simply uses an Accept or Content-Type HTTP header to specify the desired content type of the returned data, and theWeb API ensures your return value gets formatted appropriately.Rather than returning an object of type JsonResult, you simplyreturn your data object (e.g., Product or IEnumerable<Product>).
  • Automatic support for OData: By simply placing the new[Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  • Self-hosting: With the Web API,  you no longer need to use IIS to host HTTP services. Now your REST services can be hosted in a custom Windows service, console application, or any other type of host you need. 






Saturday, February 15, 2014

ASP.NET MVC 5.1 Throttling Filter

With MvcThrottle you can protect your site from aggressive crawlers, scraping tools or unwanted traffic spikes originated from the same location by limiting the rate of requests that a client from the same IP can make to your site or to specific routes. MvcThrottle is compatible with ASP.NET MVC 5.1 and can be installed via NuGet, the package is available at nuget.org/packages/MvcThrottle.

You can set multiple limits for different scenarios like allowing an IP to make a maximum number of calls per second, per minute, per hour or per day. You can define these limits to address all requests made to your website or you can scope the limits to each Controller, Action or URL, with or without query string params.
MvcThrottle filter is designed for controlling the rate of requests that clients can make to a website based on IP address, request route and client identity. You can set multiple limits for different scenarios like allowing an IP to make a maximum number of calls per second, per minute, per hour or per day. You can define these limits to address all requests made to your website or you can scope the limits to each Controller, Action or URL, with or without query string params.
Global throttling based on IP
The setup bellow will limit the number of requests originated from the same IP.
If from the same IP, in same second, you’ll make a call to 
home/index and home/about the last call will get blocked.
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        var throttleFilter = new ThrottlingFilter
        {
            Policy = new ThrottlePolicy(perSecond: 1, perMinute: 6, perHour: 9, perDay: 90)
            {
                IpThrottling = true
            },
            Repository = new CacheRepository()
        };

        filters.Add(throttleFilter);
    }
}
In order to enable throttling you’ll have to decorate your Controller or Action withEnableThrottlingAttribute, if you want to exclude a certain Action you can applyDisableThrottingAttribute.

[EnableThrottling]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [DisableThrotting]
    public ActionResult About()
    {
        return View();
    }
}
You can define custom limits using the EnableThrottling attribute, these limits will override the default ones.
[EnableThrottling(PerSecond = 2, PerMinute = 10, PerHour = 30)]
public ActionResult Index()
{
    return View();
}

Endpoint throttling based on IP
If, from the same IP, in the same second, you’ll make two calls to home/index, the last call will get blocked.
But if in the same second you call 
home/about too, the request will go through because it’s a different route.
var throttleFilter = new ThrottlingFilter
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 10, perHour: 60)
    {
        IpThrottling = true,
        EndpointThrottling = true,
        EndpointType = EndpointThrottlingType.ControllerAndAction
    },
    Repository = new CacheRepository()
};