C# 将基本身份验证添加到swagger ui,以便锁定文档页面

C# 将基本身份验证添加到swagger ui,以便锁定文档页面,c#,swagger,C#,Swagger,.Net framework 4.6.1类库项目(web API) 我已经将swagger/swashback nuget添加到项目中,并将SwaggerConfig.cs文件添加到我的App_Start文件夹中 SwiggerConfig.cs的剪报 using System.Web.Http; using WebActivatorEx; using MyService; using Swashbuckle.Application; [assembly: PreApplicationStar

.Net framework 4.6.1类库项目(web API)

我已经将swagger/swashback nuget添加到项目中,并将SwaggerConfig.cs文件添加到我的App_Start文件夹中

SwiggerConfig.cs的剪报

using System.Web.Http;
using WebActivatorEx;
using MyService;
using Swashbuckle.Application;

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
然后我继续注册服务

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "My API");
                    c.IncludeXmlComments(string.Format(@"{0}\swaggerdoc.XML",
                       System.AppDomain.CurrentDomain.BaseDirectory));
                    c.BasicAuth("basicauth").Description("Basic HTTP Authentication");
                })
            .EnableSwaggerUi(c =>
                {
                });
    }
}

但我不确定在哪里设置查看文档所需的用户名/密码。API方法都使用令牌进行身份验证,但我正试图通过使用基本身份验证来添加一层安全性,以阻止随机用户在API文档中绊倒。

如果要保护文档,必须在Web服务器本身上使用.net 4.x,我假定为IIS


您使用的方法旨在告诉Swagger显示用户名/密码登录表单,以便使用这些凭据和基本HTTP授权头调用服务端点。

要使用基本身份验证保护您的Swagger文档,您需要在SwaggerConfig.cs文件中启用它,并将其与相应的文档或操作级别的“安全”属性

请注意以下来自swagggerconfig.cs的关于启用基本身份验证的完整注释:

// You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API.
// See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details.
// NOTE: 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
//
c.BasicAuth("basic").Description("Basic HTTP Authentication");

如何将其与相应的“安全”属性耦合?您可以添加一个类来实现该过滤器,如下所示:

public class SwaggerHeaderFilter : IOperationFilter
{

    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        // check if authorization is required
        var isAuthorized = filterPipeline
            .Select(filterInfo => filterInfo.Instance)
            .Any(filter => filter is IAuthorizationFilter);
        // check if anonymous access is allowed
        var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
        if (isAuthorized && !allowAnonymous)
        {
            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();
            var auth = new Dictionary<string, IEnumerable<string>>
                 {
                    {"basic", Enumerable.Empty<string>()}
                };
            operation.security.Add(auth);
        }
    }
}
公共类SwiggerHeaderFilter:IOperationFilter
{
public void Apply(操作,SchemaRegistry SchemaRegistry,apisdescription apisdescription)
{
var filterPipeline=apiscription.ActionDescriptor.GetFilterPipeline();
//检查是否需要授权
var isAuthorized=filterPipeline
.Select(filterInfo=>filterInfo.Instance)
.Any(filter=>filter是IAAuthorizationFilter);
//检查是否允许匿名访问
var allowAnonymous=apiscription.ActionDescriptor.GetCustomAttributes

c.OperationFilter<SwaggerHeaderFilter>();