Skip to content

Instantly share code, notes, and snippets.

@cdeutsch
Created September 24, 2013 23:50
Show Gist options
  • Select an option

  • Save cdeutsch/6692982 to your computer and use it in GitHub Desktop.

Select an option

Save cdeutsch/6692982 to your computer and use it in GitHub Desktop.
using Agvise.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
namespace www.Infrastructure
{
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"Agvise\"");
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string apiKey = null;
var colonIndex = decodedToken.IndexOf(":");
if (colonIndex < 0)
{
apiKey = decodedToken;
}
else if (colonIndex == 0)
{
apiKey = decodedToken.Substring(1);
}
else
{
apiKey = decodedToken.Substring(0, colonIndex);
// password = decodedToken.Substring(colonIndex + 1);
}
using (var db = new SiteDB())
{
var customer = db.Customers.SingleOrDefault(oo => oo.ApiKey == apiKey);
if (customer != null)
{
HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(customer.Account), new string[] { });
base.OnActionExecuting(actionContext);
}
else
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"Agvise\"");
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment