Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Security in Asp.net Web API Authentication

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
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 on method like
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();
}

}
Comment
Name Email Website
Subscribe
 
Web API Security
Authentication Check


Group Training