public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void
OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if
(actionContext.Request.Headers.Authorization == null)
{
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string
authenticationString = actionContext.Request.Headers.Authorization.Parameter;
string originalString
= Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));
// Gets username and password
string useranme =
originalString.Split(':')[0];
string password =
originalString.Split(':')[1];
// Validate username and password
if
(!(useranme.Equals(System.Configuration.ConfigurationManager.AppSettings["Authorization_username"].Trim()) &&
password.Equals(System.Configuration.ConfigurationManager.AppSettings["Authorization_password"].Trim())))
{
// returns unauthorized error
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
base.OnAuthorization(actionContext);
}
}
[BasicAuthentication]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}