bug*_*ker 15 asp.net-web-api swagger
我试图让我的Web API项目使用Swagger'漂亮'文档等(http://swagger.io/)
我正在使用Swashbuckle for .NET,从NuGet安装,我使用的版本是4.0.1
我已经能够安装和使用Swagger了.此时一切似乎都很正常.我唯一的障碍是禁用API密钥并能够使用OAuth,就像在PetStore示例中一样(http://petstore.swagger.wordnik.com/#!/pet/addPet)
我已经尝试了我能在网上找到的所有东西.我在下面列出它们:
首先,这是我的Startup.cs
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
Swashbuckle.Bootstrapper.Init(config);
}
Run Code Online (Sandbox Code Playgroud)
现在,我的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();
});
}
Run Code Online (Sandbox Code Playgroud)
我有一个SwaggerExtensions文件夹,在那里我有应该需要的文件.例如:

我的课程装饰有:
[ScopeAuthorize("this.scope")]
Run Code Online (Sandbox Code Playgroud)
但是,OAuth选项永远不会在swagger页面上显示给我.我无法看到我应该能够输入自定义标题的位置.
我确实看到标题和文档描述,电子邮件地址等正在从SwaggerConfig.cs中读取,所以我知道它至少被阅读.
我无法弄清楚.:(
有任何想法吗?
我得到了解决方案.这是强大的,只是不是100%直接配置.
以下是我采取的步骤:
安装NuGet包,我用过,PM> Install-Package Swashbuckle -Version 4.1.0但链接在https://www.nuget.org/packages/Swashbuckle/,我建议得到最新的,但我知道4.1.0工作.编辑我刚刚更新到5.X它打破了它.4.1.0有效,但最新没有.我还没有进一步研究过为什么.
安装完成后,您的工作即将完成.
安装将创建一个SwaggerConfig.cs文件.这是我使用的代码(从github master复制)
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);
}
Run Code Online (Sandbox Code Playgroud)
现在我们告诉Swagger我们想要使用OAuth,这就是我们想要使用它的方式.做完了吧?不.
您需要将此文件夹和文件添加到您的解决方案中:https://github.com/domaindrivendev/Swashbuckle/tree/master/Swashbuckle.Dummy.Core/SwaggerExtensions
(你只需要.cs文件)
确保你的命名空间是正确的......
然后,您需要在WebAPI中装饰您的类,如下所示:
[ScopeAuthorize("test1")]
Run Code Online (Sandbox Code Playgroud)
现在,当您运行它并进入招摇页面时,您将看到具有该声明的每个操作都将在右上角具有OAuth开关.单击它时,您可以使用隐式授权流并获取将添加到您的请求的令牌.
这只适用于我发现的隐含授权.看起来他们似乎试图让AuthorizationCode Grant继续运行,但是他们构建的js文件只支持我所看到的内容.
希望这有助于某人.这是一个强大的工具,我希望我们看到更多的网站使用这样的东西.
谢谢,祝你好运!
小智 8
我想你原来的大部分都是好的.我正在使用Swashbuckle 5.2.1并且工作得非常好.我刚写了一篇博文(http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2/这详细解释了这一点,但要点是添加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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22825 次 |
| 最近记录: |