MVC Web API Authorization and Authentication

MVC Web API Authorization and Authentication

Hello everyone, I am going to share the code-sample to Authentication and Authorization the MVC.Net Web API 2.

·         If Web API 2 Missing header then return 404 Bad request with Authorization Token - Missing messages.
·         If Web API 2 call is unauthorized then return 401 Unauthorized  with unauthorized user.
·         If Web API 2 call is invalid then return authorization Token - Invalid messages.
·         If Web API 2 request is valid then ok.

There are fallowing steps to achieve the MVC API Authorization as given below.

Step1 : Call APIs using AJAX request.

this.getAddress = function (Ids) {
      return $http({
                        method: 'GET',
                        url: " http://localhost:9669/api/userProfile/GetAddress?id=" + Ids,
                        headers: {Authorization : '[email protected]'}
             // Write header as per you.
            });
};

Step 2: Let's start step 2 as given below.

Create a class " APIAuthorizationHandler .cs" for Authorization and Authentication to APIs and APIAuthorizationHandler is inherited to the DelegatingHandler .

Write Authentication logic in API Authorization Handler class which are given below.

namespace Employee.Models
{
    public class APIAuthorizationHandler : DelegatingHandler
    {
        // Added http response custom messages.
        private const string TokenInvalid = "Authorization Token - Invalid";
        private const string TokenMissing = "Authorization Token - Missing";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> ApplicationHeaderApiValues = null;

            // Checking the Header values
            if (request.Headers.TryGetValues("Authorization ", out ApplicationHeaderApiValues))
            {
                string[] apiKeyHeaderValue = ApplicationHeaderApiValues.First().Split(':');

                // Checking  length
                if (apiKeyHeaderValue.Length > 0)
                {
                    // Code logic after authenticate the application.
                    var appAutho = apiKeyHeaderValue[0];

                    if (appAutho.Equals(HttpContext.Current.User.Identity.Name))
                    {
                        var userNameClaim = new Claim(ClaimTypes.Name, appAutho);
                        var identity = new ClaimsIdentity(new[] { userNameClaim }, "ApplicationHeader");
                        var principal = new ClaimsPrincipal(identity);
                        Thread.CurrentPrincipal = principal;

                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                    }
                    else
                    {
                        return requestCancel(request, cancellationToken, TokenInvalid);
                    }
                }
                else
                {
                    return requestCancel(request, cancellationToken, TokenMissing);
                }
            }
            else
            {
                return requestCancel(request, cancellationToken, TokenMissing);
            }

            return base.SendAsync(request, cancellationToken);
        }

        // Web request cancel call due to missing APIID, APIID is NULL, missing all parameters etc.
        private Task<HttpResponseMessage> requestCancel(HttpRequestMessage requestMsg, CancellationToken cancellationToken, string msg)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            HttpResponseMessage responseMsg = new HttpResponseMessage();

            cancellationToken = tokenSource.Token;
            tokenSource.Cancel();

            responseMsg = requestMsg.CreateResponse(HttpStatusCode.BadRequest);
            responseMsg.Content = new StringContent(msg);

            return base.SendAsync(requestMsg, cancellationToken).ContinueWith(task =>
            {
                return responseMsg;
            });
        }
    }
}

Step : 3  Configuration to Message Handlers in Global.asax.cs class. i.e.

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Configuration to MessageHandlers for API Authorization handler.
            GlobalConfiguration.Configuration.MessageHandlers.Add(new APIAuthorizationHandler());
        }
}

The output : Please see given below the images





ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.