Web API is stateless, (means every request from client to server must have all of the required information to validate the request) and we cannot check credential from session like web application, but there are different ways we can implement security in asp.net web api, which will decide who can consume our api , means make call to api and get data or submit data.
In this tutorial you will learn how to implement security in asp.net web api using Basic HTTP Authentication, with AuthorizationFilterAttribute
Learn how to check authentication in Asp.net web API, security is an important aspect for any restful service, 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; } }
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
public class WTRAuthenticationAttribute : AuthorizationFilterAttribute
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];
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
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); } } } }
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