我已经在ASP.NET std项目中安装了Swashbuckle,并使用默认配置选项在Swagger和SwaggerUI中启用了ApiKey的选项:
GlobalConfiguration.Configuration.EnableSwagger(c =>
c.ApiKey("whatever")
.Description("API Key Authentication")
.Name("apiKey")
.In("header")
).EnableSwaggerUI(c => c.EnableApiKeySupport("apiKey", "header"));
输入apikey的选项出现在浏览器的测试ui中,但是操作并不关心我输入的内容;他们还是跑。我感到还有其他事情需要做,这句话暗示着同样的意思:
//These only define the schemes and need to be coupled with a corresponding "security" property
// at the document or operation level to indicate which schemes are required for an operation. To do this,
// you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
// according to your specific authorization implementation
但是我不太确定下一步要在Swashbuckle的上下文中做什么/打算如何工作。似乎没有任何[SwaggerXxx]
批注显然是“如果添加此批注,则只有在apikey正确的情况下,该操作才有效”
如何将我的操作/控制器方法标记为“需要有效的api键”?
我通过创建以下类实现了它:
class AuthorizeByApiKeyAttribute : Attribute, System.Web.Http.Filters.IAuthenticationFilter
{
public bool AllowMultiple => false;
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
if (context.Request.Headers.TryGetValues("apikey", out var e) && e.Contains("KEY HERE"))
context.Principal = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity("Negotiate"));
else
context.ErrorResult = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Unauthorized) as IHttpActionResult;
return Task.CompletedTask;
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
然后用[Authorize]
和[AuthorizeByApiKey]
装饰我想保护的东西>