向swagger ui添加基本身份验证,因此文档页面被锁定

时间:2019-06-27 17:07:52

标签: c# swagger

.Net Framework 4.6.1,类库项目(Web API)

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

SwaggerConfig.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文档中绊脚石。

2 个答案:

答案 0 :(得分:0)

如果要保护文档安全,则必须使用.net 4.x在Web服务器上进行此操作,我假设使用IIS。

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

答案 1 :(得分:0)

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

请注意以下SwaggerConfig.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);
        }
    }
}

,然后在swaggerConfig.cs文件中,将其添加到配置中:

c.OperationFilter<SwaggerHeaderFilter>();

别忘了用[Authorize]标签装饰Api

参考: https://codingsight.com/swashbuckle-swagger-configuration-for-webapi/