Free Web Development Online Tutorials, Learn to Code
Check Authentication in Web API, Web API C# Tutorial, Web API Security, Authentication, Authorization

Asp.net web api Authentication

How to check Authentication in Web API

In web API security is an important aspect, because the url is open to access and stateless, anyone can consume the API from different clients, but as a API developer we really need to know if the consumer is genuine, so we have to check the credential every time they make a call to our API

First we create a method to check authentication in our Web API project

public class APISecurity
{
public static bool Authenticate(string username, string password)
    {
    bool result = false;
    //Here you should write database call to check if username and password combination is correct.
    return result;
    }
}

Authentication attribute class

Now we create an authentication attribute class that can be used to check security on any controller method or on controller

In following code you will learn how to check asp net web api authentication step by step

  • How to create authentication attribute class, by inheriting from AuthorizationFilterAttribute base class
    public class WTRAuthenticationAttribute : AuthorizationFilterAttribute 
    
  • How to read authentication token from HttpActionContext
    string authTokens = actionContext.Request.Headers.Authorization.Parameter;
    string decodedAuthTokens = Encoding.UTF8.GetString(Convert.FromBase64String(authTokens));
    string[] credential = decodedAuthTokens.Split(':');
              
    string username = credential[0];
    string password = credential[1];
    
  • How to send response back
    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    
  • Finally how to call the attribute class in controller class

Here is the Custom Authorization Class

using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading;
using System.Security.Principal;
          
public class WTRAuthenticationAttribute : AuthorizationFilterAttribute          
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.Headers.Authorization == null)
        {
            actionContext.Response = actionContext.Request
            .CreateResponse(HttpStatusCode.Unauthorized);
        }
        else
        {
            string authTokens = actionContext.Request.Headers.Authorization.Parameter;
            string decodedAuthTokens = Encoding.UTF8.GetString(Convert.FromBase64String(authTokens));
            string[] credential = decodedAuthTokens.Split(':');
          
            string username = credential[0];
            string password = credential[1];
          
            if (APISecurity.Authenticate(username, password))
            {
                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
            }
            else
            {
            actionContext.Response = actionContext.Request
            .CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
    }
}

Set Authentication Attribute in Controller

Now we simply can apply this WTRAuthentication on any controller or on method like example below

[WTRAuthentication]
public class clientController : ApiController
{
            
}

Or you can also apply authentication on any method, where you want before anybody consume that method, to be authenticated
This will help you to have both secure and non-secure methods on same API

public class clientController : ApiController
{
    [WTRAuthentication]
    public IEnumerable<Client> Get()
    {
        List<Client> client = new List<Client>();
        client.Add(new Client() { ClientId = 1, CompanyName = "TATA Capital", ContactPerson = "Ratan Tata", Email = "ratantata@tata.com" });
        client.Add(new Client() { ClientId = 2, CompanyName = "Ambani Group", ContactPerson = "Anil Ambani", Email = "anil@ril.com" });
        client.Add(new Client() { ClientId = 3, CompanyName = "Godrej Steel", ContactPerson = "Adi Godrej", Email = "adi@godrej.com" });
            
    return client.ToArray();
    }            
}

So now, anyone make call to above method, will always provide the credential to get the client list

Comment
Name
Email
Website
Subscribe
 
Asp.net Web API Authentication

C# web service interview questions