Swashbuckle / Swagger-在某个操作级别/每个操作级别,我如何需要apiKey?

问题描述 投票:0回答:1

我已经在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键”?

c# asp.net swagger swashbuckle
1个回答
0
投票
[根据Mono的评论和其他一些网络资源提供的指导,我现在了解到Swashbuckle中的此设置不会向项目添加基于api密钥的身份验证,它只会导致Swashbuckle / Swagger发出描述服务的json,其中包括建议导致该服务需要具有适当值的Api Key标头(是否为真,并且在我的情况下,因为没有auth中间层,所以它不是真)]

我通过创建以下类实现了它:

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]装饰我想保护的东西>        
© www.soinside.com 2019 - 2024. All rights reserved.