Security in ASP.NET Web API.


Security can be provide in ASP.Net Web API using Authentication and Authorization.
Authentication means user identity to the system. user is able to login to a website. Example Google Account.
Authentication is provided using HTTP Module and HTTP Message Handler.

HTTP Module- You can configure your project to IIS to use built in authentication i.e; HTTP Module. It uses IPrincipal object for security under which your project is running. You can get the user identity in Thread.CurrentPrincipal. If Identity.IsAuthenticated is true then user is authenticated else user is not authenticated. It is only available to web-hosting.

HTTP Message Handler- This is more flexible as compared to HTTP Module. It can be used with both self-hosting and web-hosting. It filters all the request and pass only request that are requesting to web API route. we can provide different message handlers to different routes. we can get the identity in Thread.CurrentPrincipal.

Authorization means user rights. user is able to read and not allowed to write. Authorization is provided using Authorization Filters. We can provide filters at different level. Filters are called before any controller action.

At Global Level-  We can set filter in global file WebApiConfig.cs. This filter will authorize all the Controllers.

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}


At Controller Level-  We can specify filters to specific Controllers. This filter will authorize all the Controller actions.

[Authorize]
public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


At Action Level-  We can specify filters at action level. This filter will authorize specific action.

public class EmployeeController : ApiController
{
    [Authorize]
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


Inside Action Method-  We can customize action return result based on conditions.

public class EmployeeController : ApiController
{    
    public List<Employee> Get()
    {
       if (User.IsInRole("Manager"))
        {
          return EmployeeDAL.GetAllEmployees();
        }      
       else
        {
          //return different result
        }
    }      

    [Authorize(Users="Hitesh,Dev")] //This Action will be available for these users.
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}