How to document API Key authentication using Swashbuckle.AspNetCore v5.0.0-rc2

两盒软妹~` 提交于 2020-07-19 18:51:08

问题


I am migrating a Web API that has Swagger documenation generated using Swashbuckle from .NET Framework to ASP.NET Core. In the new AspNetCore version I'm using Swashbuckle.AspNetCore v5.0.0-rc2.

This is an internal service and authentication uses an API key provided in a custom HTTP header. In the .NET Framework application, I configured Swashbuckle to enable my API key as follows:

c.ApiKey("apiKey")
   .Description("My description")
   .Name("MyHttpHeaderName")
   .In("header);

and

c.EnableApiKeySupport("MyHtpHeaderName", "header);

How can I enable support for the same API key using Swashbuckle.AspNetCore v5.0.0-rc2?

Much of the information I've found by searching seems to relate to versions of Swashbuckle.AspNetCode prior to v5.0.0-rc2.

This answer is for v5.0.0-rc2 but only covers Bearer Authorization, and doesn't seem to relate to using a custom HTTP header: https://stackoverflow.com/a/57872872/13087


回答1:


In Swashbuckle.AspNetCore, the authorization setup is all handled with the AddSecurityDefinition method.

In 4.x, you could set up an ApiKeyScheme that describes how to use an API key to authorize requests:

c.AddSecurityDefinition("ApiKey", new ApiKeyScheme()
{
    Description = "My description",
    Name = "MyHttpHeaderName",
    In = "header",
});

Starting with 5.x, Swashbuckle.AspNetCore is no longer using its own models but instead relies on OpenAPI.NET. This means that the above security definition would look like this in 5.x:

c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme()
{
    Type = SecuritySchemeType.ApiKey,
    In = ParameterLocation.Header,
    Name = "MyHttpHeaderName",
    Description = "My description",
});

Note that you will also have to set up security requirements to configure which security definition is required for what operations. In 5.x, the syntax for that will look like this:

c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKey" }
        },
        new string[] { }
    }
});

You can read more about all this in the documentation on security definitions and requirements.



来源:https://stackoverflow.com/questions/57943550/how-to-document-api-key-authentication-using-swashbuckle-aspnetcore-v5-0-0-rc2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!