Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Basic Authentication in ASP.Net Web API

In this article, you will learn how to create a custom authentication filter and implement basic authentication web api. In the previous tutorial, I have explained What are filters in ASP.Net Web API so now I am going to implement an authentication filter for securing web api using basic authentication.

Basic authentication is a simple authentication scheme built into the HTTP protocol. The client sends HTTP requests with the Authorization the header that contains the word Basic followed by a space and a base64-encoded string username: password.

How to add Basic Authentication in Web API

In this example, we are willing to check the user authenticity with the help of filters so you need to implement a custom authentication filter. I am using the last sample here if you will see we just written the code for creating the custom filters but we didn’t implement all these methods.

This authentication filter will help you when implementing the locking through the basic authentication like windows authentication and it might be through the bearer token also so in every case we will use this authentication filter.

So here I am assuming that we will pass the token from the client end and that token validity we will check here. I am not using any database because we just need to understand the workflow of the authentication filter so first of all here let’s understand what are the various implementation we need to do here. Find the below source code:-

CustomAuthenticationFilter.cs

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
using System.Web.Http.Results;

namespace WebAPIFilter.Filters
{
    public class CustomAuthenticationFilter : Attribute, IAuthenticationFilter
    {
        public bool AllowMultiple => false;

        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            HttpRequestMessage request = context.Request;
            AuthenticationHeaderValue authorization = request.Headers.Authorization;

            if (authorization == null)
            {
                context.ErrorResult = new AuthenticationFailureResult("Missing Authorization", request);
                return;
            }
            if (authorization.Scheme != "Bearer")
            {
                context.ErrorResult = new AuthenticationFailureResult("Invalid Authorization Scheme", request);
                return;
            }

            if (String.IsNullOrEmpty(authorization.Parameter))
            {
                context.ErrorResult = new AuthenticationFailureResult("Missing Token", request);
                return;
            }

            bool checkToken = await ValidateTokenAsync(authorization.Parameter);
            if (!checkToken)
                context.ErrorResult = new AuthenticationFailureResult("Invalid Token", request);
            return;
        }

        private Task ValidateTokenAsync(string parameter)
        {
            //TO DO: Validate Token

            if (parameter == "123456")
                return Task.FromResult(true);
            else
                return Task.FromResult(false);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            if (context.Result is AuthenticationFailureResult)
            {
                var challenge = new AuthenticationHeaderValue[]
                {
                    new AuthenticationHeaderValue("Bearer","")
                };
                context.Result = new UnauthorizedResult(challenge, context.Request);
                return Task.FromResult(context.Result);
            }
            else
                return Task.FromResult(0);
        }
    }
}

AuthenticationFailureResult.cs

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net;
namespace WebAPIFilter.Filters
{
    public class AuthenticationFailureResult : IHttpActionResult
    {
        private string ReasonPhrase;
        private HttpRequestMessage Request;

        public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
        {
            this.ReasonPhrase = reasonPhrase;
            this.Request = request;
        }

        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            response.RequestMessage = Request;
            response.ReasonPhrase = ReasonPhrase;
            return Task.FromResult(response);
        }
    }
}

ProductController.cs

using System.Collections.Generic;
using System.Web.Http;
using WebAPIFilter.Filters;

namespace WebAPIFilter.Controllers
{
    //[CustomAuthenticationFilter]
    public class ProductController : ApiController
    {
        [CustomAuthenticationFilter]
        public IEnumerable GetAll()
        {
            return new string[] { "laptop", "mobile", "xbox" };
        }

        [OverrideAuthentication]
        [OverrideAuthorization]
        public string Get(int id)
        {
            return "laptop";
        }
    }
}
Authorization filter
Authorization filter passing authorization bearer token header

Download Source Code

Conclusion

I hope you liked this article on Http Basic Authentication Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

The post Basic Authentication in ASP.Net Web API appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

Basic Authentication in ASP.Net Web API

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×