Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created August 28, 2014 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RhysC/140750961f1bdaab4426 to your computer and use it in GitHub Desktop.
Save RhysC/140750961f1bdaab4426 to your computer and use it in GitHub Desktop.
RequireApiKey require an api key for MVC controllers assumes SSL
public class RequireApiKey : ActionFilterAttribute
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(RequireApiKey));
public override void OnActionExecuting(HttpActionContext context)
{
var ipAddress = GetIpAddress(context);
Logger.InfoFormat("API attempt. Uri {0} - IP {1} - Headers {2} ", context.Request.RequestUri, ipAddress, context.Request.Headers);
IEnumerable<string> values;
if (context.Request.Headers.TryGetValues("ApiKey", out values) && GetApiKeys().Any (x => x ==values.First())
{
context.RequestContext.Principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, Constants.Roles.Api) }));
base.OnActionExecuting(context);
return;
}
Logger.WarnFormat("Unauthorised API attempt. Uri {0} - Headers {1} ", context.Request.RequestUri, context.Request.Headers);
context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Missing ApiKey") };
}
private static string GetIpAddress(HttpActionContext actionContext)
{
var context = actionContext.Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;
return context == null ? "Unknown" : context.Request.UserHostAddress;
}
private IEnumerable<string> GetApiKeys()
{
//todo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment