Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created March 31, 2014 11:03
Show Gist options
  • Select an option

  • Save AlexArchive/9889949 to your computer and use it in GitHub Desktop.

Select an option

Save AlexArchive/9889949 to your computer and use it in GitHub Desktop.
public class MustBeAuthorizedAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
return;
}
var authHeader = actionContext.Request.Headers.Authorization;
if (authHeader != null)
{
if (authHeader.Scheme == "Basic" && !string.IsNullOrEmpty(authHeader.Parameter))
{
try
{
var credentials = ExtractCredentials(authHeader.Parameter);
var username = credentials[0];
var password = credentials[1];
if (username == "administrator" && password == "password")
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
Thread.CurrentPrincipal = currentPrincipal;
}
}
catch
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
private static string[] ExtractCredentials(string authParam)
{
var credentials = Encoding.Default.GetString(Convert.FromBase64String(authParam));
return credentials.Split(':');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment