我开发了一个 .NET Core Web API,它将使用一些 API 密钥身份验证。它不是面向用户的 API,而是由其他一些应用程序调用,因此我想要多个 API 密钥,每个应用程序一个。
为了解决这个问题,我编写了以下 ApiKeyAttribute。
[AttributeUsage(validOn: AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class ApiKeyAttribute : Attribute, IAsyncActionFilter
{
private const string API_KEY_HEADER = "z-api-key"; //This is the name we are looking in the headers for the value
private const string DUMMY_KEY = "dummy-key-do-not-use"; //Testing key only REMOVE.
private List<string> ApiKeyCache = new List<string>();
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var keyHeaderExists = context.HttpContext.Request.Headers.TryGetValue(API_KEY_HEADER, out var keyHeaderValue);
if (!keyHeaderExists)
{
context.Result = new BadRequestObjectResult($"No api key was provided. Please provide a key in the '{API_KEY_HEADER}' header.");
return;
}
//TODO: Some proper api key validation once we have agreed how best to do it...
if (!ApiKeyCache.Contains(keyHeaderValue))
{
//Do the checks in the database/key vault secrets or where ever it maybe... then add it to the cache if its valid.
}
if (keyHeaderValue != DUMMY_KEY)
{
context.Result = new BadRequestObjectResult($"The provided api key is not authorised.");
return;
}
await next();
}
}
这符合我的预期,但我对以下内容提出了一些建议。
答案 0 :(得分:0)
在应用配置中存储配置密钥的最佳方式。
但是如果要存储在数据库中,则必须先解密为base64并存储在数据中。但是这种方法可能需要更多的代码行来解密和加密然后代码