Asp.net web api 使用Swagger/swashback的OAUTH Web API

Asp.net web api 使用Swagger/swashback的OAUTH Web API,asp.net-web-api,swagger,Asp.net Web Api,Swagger,我正试图让我的Web API项目使用招摇过市的“漂亮”文档等() 我使用的是从NuGet安装的Swashback for.NET,我使用的版本是4.0.1 我已经能够安装和使用斯威格。在这一点上,一切似乎都很正常。我面临的唯一障碍是禁用API密钥,并能够使用OAuth,就像在PetStore示例()中一样 我在网上找到的东西都试过了。让我把它们列在下面: 首先,这是我的Startup.cs public void Configuration(IAppBuilder app) { var

我正试图让我的Web API项目使用招摇过市的“漂亮”文档等()

我使用的是从NuGet安装的Swashback for.NET,我使用的版本是4.0.1

我已经能够安装和使用斯威格。在这一点上,一切似乎都很正常。我面临的唯一障碍是禁用API密钥,并能够使用OAuth,就像在PetStore示例()中一样

我在网上找到的东西都试过了。让我把它们列在下面:

首先,这是我的Startup.cs

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();

    WebApiConfig.Register(config);

    Swashbuckle.Bootstrapper.Init(config);
}
现在,我的SwaggerConfig.cs:

public static void Register()
{
    Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);

    SwaggerSpecConfig.Customize(c =>
    {
        c.IgnoreObsoleteActions();

        c.IncludeXmlComments(GetXmlCommentsPath());

        c.ApiInfo(new Info
        {
            Title = "Work you",
            Description = "testing some stuffs",
            Contact = "Email@email.com"
        });

        c.Authorization("oauth2", new Authorization
        {
            Type = "oauth2",
            Scopes = new List<Scope>
                {
                    new Scope { ScopeId = "products.read", Description = "View products" },
                    new Scope { ScopeId = "products.manage", Description = "Manage products" }
                },
            GrantTypes = new GrantTypes
            {
                ImplicitGrant = new ImplicitGrant
                {
                    LoginEndpoint = new LoginEndpoint
                    {
                        Url = "https://www.mysecure.website.com"
                    },
                    TokenName = "access_token"
                }
            }
        });
    });


    SwaggerUiConfig.Customize(c =>
    {
        c.EnableOAuth2Support("client_id", "test-realm", "app Name");

        var thisAssembly = typeof(SwaggerConfig).Assembly;

        c.SupportHeaderParams = true;
        c.DocExpansion = DocExpansion.List;
        c.SupportedSubmitMethods = new[] { HttpMethod.Get, HttpMethod.Post, HttpMethod.Put, HttpMethod.Head };
        c.EnableDiscoveryUrlSelector();

    });

}
但是,OAuth选项从未在“招摇过市”页面上为我显示。我也看不到应该在哪里输入自定义标题

我确实看到标题和文档描述、电子邮件地址等正在从swagggerconfig.cs读取,所以我知道至少正在读取

我想不出来(


有什么想法吗?

默认情况下,swagger ui不显示OAuth2集成

要启用它,您需要遵循以下步骤:

  • 确保
    包含在index.html顶部的脚本列表中。默认情况下,它应该在那里
  • 在index.html底部的SwaggerUi声明中,取消对以下代码段的注释(默认情况下,它在那里并已注释):


  • 您可能希望使用自己的设置修改
    clientId
    领域
    appName

    我得到了我的解决方案。这很强大,只是不是100%直接配置

    以下是我采取的步骤:

    安装NuGet软件包,我使用了
    PM>安装软件包Swashback-Version 4.1.0
    ,但链接在,我建议使用最新版本,但我知道4.1.0有效。EDIT我刚刚更新到5.X,它破坏了它。4.1.0有效,但最新版本没有。我还没有进一步研究原因

    一旦你安装了它,你的工作就差不多完成了

    安装将创建一个SwaggerConfig.cs文件。这是我使用的代码(从github master复制)

    现在,当您运行它并进入swagger页面时,您将看到每个具有该声明的操作将在右上角具有OAuth开关。单击它时,您可以使用隐式授权流并获得一个令牌,该令牌将添加到您的请求中

    这只适用于我所发现的隐式授权。看起来他们确实试图获得AuthorizationCode授权,但他们构建的js文件仅支持我所看到的隐式授权

    希望这能帮助一些人。这是一个强大的工具,我希望我们看到更多的网站使用这样的东西


    谢谢你,祝你好运!

    我想你最初的大部分都还可以。我使用的是Swashback 5.2.1,运行得很好。我刚刚写了一篇博客()详细解释了这一点,但要点是添加了OperationFilter类定义哪些API方法将在其上获得OAuth21切换按钮GitHub的SwaggerExtensions文件夹中的定义如上所述,但实际上您所需要的只是至少一个实现IOperationFilter及其Apply方法的类。下面我有一个示例类。类名真的不重要(也不重要在哪里),您只需要包含它(以及其他任何类,如果您有更多)在指定OperationFilter的SwaggerConfig中

     public class AssignOAuth2SecurityRequirements : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();
            var allowsAnonymous = actFilters.Select(f => f.Instance).OfType<OverrideAuthorizationAttribute>().Any();
            if (allowsAnonymous)
                return; // must be an anonymous method
    
    
            //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
            //    .Select(filterInfo => filterInfo.Instance)
            //    .OfType<AllowAnonymousAttribute>()
            //    .SelectMany(attr => attr.Roles.Split(','))
            //    .Distinct();
    
            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();
    
            var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
            {
                {"oauth2", new List<string> {"sampleapi"}}
            };
    
            operation.security.Add(oAuthRequirements);
        }
    }
    
    公共类分配OAuth2安全要求:IOperationFilter
    {
    public void Apply(操作,SchemaRegistry SchemaRegistry,apisdescription apisdescription)
    {
    var actFilters=apiscription.ActionDescriptor.GetFilterPipeline();
    var allowsAnonymous=actFilters.Select(f=>f.Instance).OfType().Any();
    如果(允许匿名)
    return;//必须是匿名方法
    //var scopes=apiscription.ActionDescriptor.GetFilterPipeline()
    //.Select(filterInfo=>filterInfo.Instance)
    //第()类
    //.SelectMany(attr=>attr.Roles.Split(','))
    //.Distinct();
    if(operation.security==null)
    operation.security=新列表();
    var oAuthRequirements=新字典
    {
    {“oauth2”,新列表{“sampleapi”}
    };
    operation.security.Add(oAuthRequirements);
    }
    }
    
    我如何告诉swagger在获取令牌时需要请求哪些作用域?在SwaggerConfig.cs文件中,有一个OAuth2部分,该部分最终看起来应该是这样的(最初被注释掉):c.OAuth2(“OAuth2”)….作用域(scopes=>{scopes.Add(“managerapi”,“DESCRIPTION”);};“oauth2”字符串必须与我的orig响应中显示的字符串匹配。
        /*
        initOAuth({
          clientId: "your-client-id",
          realm: "your-realms",
          appName: "your-app-name"
        });
        */
    
    public class SwaggerConfig
        {
            public static void Register()
            {
                Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);
    
                SwaggerSpecConfig.Customize(c =>
                {
                    c.IgnoreObsoleteActions();
    
                    //c.SupportMultipleApiVersions(
                    //    new[] { "1.0", "2.0" },
                    //    ResolveVersionSupportByRouteConstraint);
    
                    //c.PolymorphicType<Animal>(ac => ac
                    //    .DiscriminateBy(a => a.Type)
                    //    .SubType<Kitten>());
    
                    c.OperationFilter<AddStandardResponseCodes>();
                    c.OperationFilter<AddAuthResponseCodes>();
                    c.OperationFilter<AddOAuth2Scopes>();
    
                    //c.IncludeXmlComments(GetXmlCommentsPath());
    
                    c.ApiInfo(new Info
                    {
                        Title = "Swashbuckle Dummy",
                        Description = "For testing and experimenting with Swashbuckle features",
                        Contact = "someone@somewhere.com"
                    });
    
                    c.Authorization("oauth2", new Authorization
                    {
                        Type = "oauth2",
                        Scopes = new List<Scope>
                            {
                                new Scope { ScopeId = "test1", Description = "test1" },
                                new Scope { ScopeId = "test2", Description = "test2" }
                            },
                        GrantTypes = new GrantTypes
                        {
                            ImplicitGrant = new ImplicitGrant
                            {
                                LoginEndpoint = new LoginEndpoint
                                {
                                    Url = "https://your.Oauth.server/Authorize"
                                },
                                TokenName = "access_token"
                            }
                        }
                    });
                });
    
                SwaggerUiConfig.Customize(c =>
                {
                    var thisAssembly = typeof(SwaggerConfig).Assembly;
    
                    c.SupportHeaderParams = true;
                    c.DocExpansion = DocExpansion.List;
                    c.SupportedSubmitMethods = new[] { HttpMethod.Get, HttpMethod.Post, HttpMethod.Put, HttpMethod.Head };
                    //c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "WebApplication4.SwaggerExtensions.onComplete.js");
                    //c.EnableDiscoveryUrlSelector();
                    //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
                    //c.InjectStylesheet(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
    
                    c.EnableOAuth2Support("client_id", "realm", "Swagger UI");
                });
                // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ...
            }
            private static string GetXmlCommentsPath()
            {
                return String.Format(@"{0}\XmlComments.xml", AppDomain.CurrentDomain.BaseDirectory);
            }
    
    [ScopeAuthorize("test1")]
    
     public class AssignOAuth2SecurityRequirements : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();
            var allowsAnonymous = actFilters.Select(f => f.Instance).OfType<OverrideAuthorizationAttribute>().Any();
            if (allowsAnonymous)
                return; // must be an anonymous method
    
    
            //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
            //    .Select(filterInfo => filterInfo.Instance)
            //    .OfType<AllowAnonymousAttribute>()
            //    .SelectMany(attr => attr.Roles.Split(','))
            //    .Distinct();
    
            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();
    
            var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
            {
                {"oauth2", new List<string> {"sampleapi"}}
            };
    
            operation.security.Add(oAuthRequirements);
        }
    }