【问题标题】:Add basic auth to swagger ui so the documentation pages are locked down将基本身份验证添加到 swagger ui,以便锁定文档页面
【发布时间】:2019-06-27 17:07:52
【问题描述】:

.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 文档。

【问题讨论】:

    标签: c# swagger


    【解决方案1】:

    如果您想保护文档,您必须在网络服务器本身上进行此操作,使用 .net 4.x 我假设是 IIS。

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

    【讨论】:

      【解决方案2】:

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

      请注意以下来自 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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        相关资源
        最近更新 更多