Thursday 19 April 2018

Provide security to Your WebApi using HttpMessageHandler


Using of HttpMessageHandler, help you to secure your WebApi action method, Even though it’s not the full proof security. But it is good to provide security based on tokens.

Step 1: Create A Web API project.
Follow below:

Step 2: Add a class file and giving the name as:

That You can give as any name








Step 3:   Now you need to inherit the class  DelegatingHandler and implement the  method as SendAsync.
In side of that you need to check with the request for token has passed or not. Using of HttpMessageHandler.

namespace WebServiceUnitTest.Handlers
{

  
    public class CustomSecurityTokenMessageHandler : DelegatingHandler
    {
        private static string _tokenName = "my_Api_token";
        private static string _tokenValue = "abc12345";


        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
         
           if(request.Headers.Contains(_tokenName) && request.Headers.GetValues(_tokenName).First() == _tokenValue)
            {
                return await base.SendAsync(request,cancellationToken);
            }
            else
            {
                var response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "Un-Authorized");
                return response;
            }
          
        }
    }
}

In Above Code you can see the Checking the request Header contains that particular token or not, than need to check that tokenvalue is same or not.
request.Headers.Contains(_tokenName) && request.Headers.GetValues(_tokenName).First()

If it won’t match it will give the error as Forbidden and un-Authorized.
request.CreateErrorResponse(HttpStatusCode.Forbidden, "Un-Authorized");

You can see the Error in Developer tool like.


Step 4 : To Consuming the Web API you need to pass the token along with the request you should have below code.
<script>

        function refresh() {
          
            $("#Output").html("");

            $.getJSON("http://localhost:49531/api/Customer")
                .done(function (data) {
                  
                    $.each(data, function (key, item) {
                        $('<li>' + item.CustomerName +  '</li>').appendTo($('#Output'));
                    });
                });
           
        }


        function RequestWithToken() {

            $("#Output").html("");

            $.ajaxSetup
                ({
                    type: "GET",
                    headers: {
                        "my_Api_token": "abc12345"
                    }
                });

        }
        RequestWithToken();
        refresh();
      
    </script>

Now in above code you can see the method RequestWithToken will pass the token and value for each get request in header.
                    headers: {
                        "my_Api_token": "abc12345"
                    }

You can see the response by passing token.



And the header will have that value that we pass.


No comments:

Post a Comment