ASP.Net Web API Security

If you are new to ASP.Net Web API then please start from the beginning level. What is ASP.Net Web API? In the previous blog, I wrote about Routing in Web API. You may also like .Net Core Introduction and MicroService Architecture.

I have also explained, How to create a secure Web API? in my earlier blog.
In this blog, let's discuss the Web API security in details.


Web API security means, you want to control your Web API and decide who can access the API and who can't access the Web API.

Authorization and Authentication in ASP.Net Web API.

So, you have created your Web API, right? If not, then go through with my earlier blog - Create ASP.Net Web API

Now, I assume your Web API is ready but you want to apply some level of security.

Lets' first understand Authorization and Authentication, then later we will discuss how to implement Authentication and Authorization on Web API.

Authentication is the process of identifying a user by his/her credentials for eg username and password.

Authorization is used to decide whether a particular logged in user has access to perform an action or not.

Authentication in Web API

Your Web API can be accessed by anyone who knows the URL. This is not a good practice in the context of security.

There are various ways to secure Web API. Let's discuss one by one.

Forms Authentication

Forms authentication is the traditional approach to authenticate ASP.Net Web Forms, MVC and now Web API. Forms authentication works on a ticket base mechanism. 

A ticket gets created to authenticate logged in user and stored in cookies and this ticket is used for all subsequent request to make sure user is authentic.

Forms Authentication works with 2 elements added in web.config file.


<authentication mode="Forms">     
 <forms loginUrl="/login.aspx"/> 
</authentication>
<authorization>         
<deny users="?"/> 
</authorization>

Authorization in Web API

Once user has been authenticated to Web API, now its time to authorize the user i.e. what access they have.

Authorization Filter

Authorize Filter is a special attribute decorated with specific action level to authorize a logged in user. There could be multiple Authorize filter for a single action.

Restrict access to a specific action then add [Authorize] attribute to that action method.

public class TestController : ApiController
    {

        public string Get()
        {
            return "All product";
        }

        [Authorize]
        public string Get(int id)
        {
            return "Product Details";
        }
    }


Restrict access to a specific controller then add [Authorize] attribute to that Controller.
This will restrict all action in the controller.

[Authorize]
    public class TestController : ApiController
    {

        public string Get()
        {
            return "All product";
        }

        public string Get(int id)
        {
            return "Product Details";
        }
    }


Restrict a specific controller and allow only one action method from that controller as anonymous and other as restricted.

In below code, all action method within TestController is restricted but Get() is anonymous. This is because an extra attribute has been added to Get action method.


[Authorize]
    public class TestController : ApiController
    {
        [AllowAnonymous]
        public string Get()
        {
            return "All product";
        }

        public HttpResponseMessage POST(int id)
        {
            //Write code here
        }
    }

Authorize filter based on User Role


    [Route("api/[controller]")]
    [Authorize(Roles = "StoreKeeper")]
    public class ECommerceController : Controller
    {
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<Store> Get()
        {
            return new List<Store>()
            {
                new Store() {pid = "1", prdname= "Prd1",qty = 100, price = 200 },
                new Store() {pid = "2", prdname= "Prd2",qty = 120, price = 110 }
            };

         }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        [Authorize(Roles = "StoreManager")]
        public void Delete(int id)
        {
            //Delete the product details based on id
        }
    }

    public class Store
    {
       public string pid { get; set; }
        public string prdname { get; set; }
        public int qty { get; set; }
        public decimal price { get;set }
    }

Global Authorization Filter

If you want to apply Authorize filter on every Web API controller, add AuthorizeAttribute globally in WebAPIConfig.cs file


public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { controller= "order", id = RouteParameter.Optional }
            );

            config.Filters.Add(new AuthorizeAttribute);
        }



Prev Blog- Routing in Web API
Next Blog - Media Formatter in Web API

Keep following SharePointCafe.Net

Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers