Web API Basic Authentication Using MVC
Step :1 Create WEB API Application
Step :2 Create Authorization Filter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Test.BussinessLayer;
namespace Test.Web.API
{
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
private const string keyName = "TestName";
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized)
{
actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic auth=\"{0}\"", keyName));
}
}
else
{
string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
string username = usernamePasswordArray[0];
string password = usernamePasswordArray[1];
if (UserValidate.Login(username, password))
{
var identity = new GenericIdentity(username);
IPrincipal principal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null) { HttpContext.Current.User = principal; }
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
}
Step :3 Create Method For Validate User
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.DataAccessLayer;
namespace Test.BussinessLayer
{
public class UserValidate
{
//This method is used to check the user credentials
public static bool Login(string username, string password)
{
return new UserFactory().UserValidate(username, password);
}
}
}
Step :4 Create Method to check user exist into database
return TRUE when yes other wise FALSE.
Step :5 User the filter attribute
Use the "[BasicAuthentication]" filter attribute above controller action method.