-
-
Save LSTANCZYK/b3d4cb2dccad8913da4784893dc55688 to your computer and use it in GitHub Desktop.
RequireApiKey require an api key for MVC controllers assumes SSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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