How to create secure Web API in asp.net

In my earlier blog I wrote about how to create a web api in asp.net , now your WebAPIi is ready to work.

Web API security is very important especially if you are allowing it to external users to consume it.
Now suppose you want to control your web api in the context of security. How you will achieve this because security is much more needed essentials than any other things in software development.

One way is to use [Authorize] attribute before your controller class like below.
This will disallow the anonymous access for all HTTP verbs implemented in below API.

Table of Contents

   

 [Authorize]

    public class TestController : ApiController

    {

      

        static List<string> empList = new List<string>()

        {

        “Sachin”,“Rahul”,“Laxman”,“MS”“Virendar”

        };

      

        public IEnumerable<string> GetAll()

        {

            return empList;

        }

       

        public string GetByID(int id)

        {

            return empList[id];

           

        }

        public void Insert([FromBody]string value)

        {

            empList.Add(value);

        }

        public void Update(int id, [FromBody]string value)

        {

            empList[id] = value;

        }

        public void DeleteRecord(int id)

        {

            empList.RemoveAt(id);

        }

        public void DeletebyName(string emp)

        {

            empList.Remove(emp);

        }

    }

I have used Google Chrome extensions called “POSTMAN” there are other tools like Telerik Fiddler


If you wish to allow only Get operation to be accessed anonymously, then you may use [AllowAnonymous] attribute with that operation/function like below.

        [AllowAnonymous]
        public string GetByID(int id)
        {
            return empList[id];
        }

So in above case only GetById operation can be accessed anonymously and others are not.
asp.net web api

You may define a role for the reauthorized user for eg – A specific operation can be accessed by a user whose role is Manager or Admin.

I will write more on Web API security.
Please subscribe to my blog, comment if you like my blog and like facebook page.
Happy Coding.

Leave a Comment

RSS
YouTube
YouTube
Instagram