Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created August 4, 2015 15:23
Show Gist options
  • Save hanssens/b939e38b3cc2860d01fc to your computer and use it in GitHub Desktop.
Save hanssens/b939e38b3cc2860d01fc to your computer and use it in GitHub Desktop.
BasicAuthAttribute - Attribute that validates the provided credentials in the XHR header of an AJAX request.
/// <summary>
/// Attribute that validates the provided credentials in the XHR header of an AJAX request.
/// </summary>
/// <example>
/// Example call:
/// http://stackoverflow.com/a/11960692/1039247
/// </example>
public class BasicAuthAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// check if a header is available
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
// fetch the token
var authToken = actionContext.Request.Headers.Authorization.Parameter;
var decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
var username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
var password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
// TODO: Validate username/password here
}
// finish executing the action
base.OnActionExecuting(actionContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment