Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Created July 10, 2018 14:48
Show Gist options
  • Save GeorgDangl/87db6426962bf50933b093e0952570e1 to your computer and use it in GitHub Desktop.
Save GeorgDangl/87db6426962bf50933b093e0952570e1 to your computer and use it in GitHub Desktop.
Using Policy Based API Key Authorization in ASP.NET Core
public class ApiKeyRequirement : IAuthorizationRequirement
{
public IReadOnlyList<string> ApiKeys { get; set; }
public ApiKeyRequirement(IEnumerable<string> apiKeys)
{
ApiKeys = apiKeys?.ToList() ?? new List<string>();
}
}
public class ApiKeyRequirementHandler : AuthorizationHandler<ApiKeyRequirement>
{
public const string API_KEY_HEADER_NAME = "X-API-KEY";
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
{
SucceedRequirementIfApiKeyPresentAndValid(context, requirement);
return Task.CompletedTask;
}
private void SucceedRequirementIfApiKeyPresentAndValid(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
{
if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
{
var apiKey = authorizationFilterContext.HttpContext.Request.Headers[API_KEY_HEADER_NAME].FirstOrDefault();
if (apiKey != null && requirement.ApiKeys.Any(requiredApiKey => apiKey == requiredApiKey))
{
context.Succeed(requirement);
}
}
}
}
public class MyController : Controller
{
[Authorize(Policy = "ApiKeyPolicy")]
public async Task<IActionResult> DoSensitiveOperation()
{
// This action can only be called if the request has a correct
// api key attached
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IAuthorizationHandler, ApiKeyRequirementHandler>();
services.AddAuthorization(authConfig =>
{
authConfig.AddPolicy("ApiKeyPolicy",
policyBuilder => policyBuilder
.AddRequirements(new ApiKeyRequirement(new[] { "my-secret-key" })));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment