首页 文章

使用Swashbuckle和ASP.NET Identity限制对Swagger中某些API控制器的访问

提问于
浏览
10

所以,我开始使用Swagger . 我完全爱上了它的功能,但我对所有公开方法的可用性都有所怀疑 .

据我所知 - Swaschbuclke中包含的所有“auth”方法实际上都是关于API本身,但我不需要帮助 - 我的所有API都受API id /密钥对的保护 .

我想以某种方式利用ASP.NET身份(登录系统)来限制对API页面的访问(/ swagger / ui / index) .

有什么办法吗? Swaschbuckle中的任何方法?任何路线/身份黑客?

任何帮助表示赞赏 .

编辑1: [ApiExplorerSettings(IgnoreApi = true)] 属性不是我正在寻找的 - 它限制了对方法的所有访问,无论身份如何 .

2 回答

  • 16

    在项目根目录中创建名为“swagger”的新文件夹 . 文件夹名称应与swagger文档的url相匹配 .

    在新创建的文件夹中添加了新的Web.config文件 .

    <configuration> 
    <system.web> 
    <authorization> 
    <deny users="?" /> 
    </authorization> 
    </system.web> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true" /> 
    </system.webServer> 
    </configuration>
    

    回答发现here .

    另一种选择是:

    “在我的头脑中,我会说在这里你需要一个DelegatingHandler . ”

    回答发现here .

  • 1

    关于在swagger文档中限制单个API的暴露:

    Swashbuckle 5.x:

    Swashbuckle 5.x有一个名为IgnoreObsoleteActions的配置选项(您需要设置它;默认情况下不启用它),如果它们具有 [Obsolete] 属性,它将隐藏操作 .

    示例:配置

    httpConfiguration
        .EnableSwagger(c =>
            {
                c.IgnoreObsoleteActions();
            });
    

    更多信息请参见documentation .

    Swashbuckle 4.1.x (or if you don't want to use the obsolete attribute):

    Swashbuckle在IApiExplorer之上构建了一个swagger文档 . 您应该能够添加一个属性 - [ApiExplorerSettings(IgnoreApi = true)] - 来管理ApiExplorer设置控制器类或单个控制器方法,以便在生成文档时让资源管理器(以及随后的Swashbuckle)忽略它们 .

    示例:个人行动

    /// Ignore 'GetFoo' in documentation
    public class FooBarController
    {
        [ApiExplorerSettings(IgnoreApi = true)]
        public Bar GetFoo
        {
           ...
        }
    
        public Bar GetBar
        {
           ...
        }
    }
    

    示例:控制器类

    /// Ignore every controller method in FooBarController in documentation
    [ApiExplorerSettings(IgnoreApi = true)]
    public class FooBarController
    {
        public Bar GetFoo
        {
           ...
        }
    
        public Bar GetBar
        {
           ...
        }
    }
    

    GitHub Issue中的更多细节 . 我自己在Swashbuckle 4.1.x中使用过它 .

相关问题