【问题标题】:Swagger and WebAPI (Swashbuckle) - making the /swagger endpoint private?Swagger 和 WebAPI (Swashbuckle) - 将 /swagger 端点设为私有?
【发布时间】:2016-08-04 01:09:10
【问题描述】:

我刚刚在我的 WebAPI 项目中安装了 Swashbuckle,到目前为止一切顺利,尽管 /swagger api 端点是公共的。

我想只允许我的移动应用开发者访问。如何将我的 API 隐藏在密码后面或在此处要求表单身份验证?

【问题讨论】:

    标签: asp.net-web-api swagger swashbuckle


    【解决方案1】:

    我通过以下方式实现了这一点:

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
            string username = null;
            if (Thread.CurrentPrincipal.Identity != null && Thread.CurrentPrincipal.Identity.Name != null) {
                username = Thread.CurrentPrincipal.Identity.Name.ToLower();
            }
            if (IsSwagger(request) && username != "Admin") {
                var response = request.CreateResponse(HttpStatusCode.Unauthorized);
                return Task.FromResult(response);
            }
            else {
                return base.SendAsync(request, cancellationToken);
            }
        }
    
        private bool IsSwagger(HttpRequestMessage request) {
            return request.RequestUri.PathAndQuery.StartsWith("/swagger");
        }
    

    【讨论】:

      【解决方案2】:

      如果您的项目托管在 IIS 下,您可以在 IIS 网站上使用Windows(对站点文件夹具有适当的访问权限)或basic authentication,并禁用匿名身份验证。

      【讨论】:

        【解决方案3】:

        @bsoulier 的回答是完全合理的。另一种方法是使用 JavaScript/AJAX。

        我没有尝试保护实际的 swagger-ui 索引页面,因为大多数时候端点上的身份验证就足够了。

        但是任何 JavaScript 都可以轻松注入index 页面,或者您可以使用自己的自定义index 页面。这意味着您可以使用任何您想要的身份验证。只需创建一个简单的 HTML 表单并使用 AJAX 调用以在允许用户查看任何内容或将其重定向到真正的 swagger-ui 页面之前登录用户。

        SwaggerConfig将JavaScript文件注入swagger-ui页面:

        c.InjectJavaScript(thisAssembly, "Your.Namespace.testScript1.js");
        

        将自定义索引页面从SwaggerConfig注入到swagger-ui页面中:

        c.CustomAsset("index", containingAssembly, "Your.Namespace.index.html");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-12
          • 1970-01-01
          • 1970-01-01
          • 2019-04-25
          相关资源
          最近更新 更多