我能够让这个工作。大部分都可以找到答案here http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2/.
为了让 client_credential 授权发挥作用,我必须更改一些部分。
第一部分位于 EnableSwagger 和 EnableSwaggerUi 调用中:
config.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "sample api");
c.OAuth2("oauth2")
.Description("client credentials grant flow")
.Flow("application")
.Scopes(scopes => scopes.Add("sampleapi", "try out the sample api"))
.TokenUrl("http://authuri/token");
c.OperationFilter<AssignOAuth2SecurityRequirements>();
}).EnableSwaggerUi(c =>
{
c.EnableOAuth2Support("sampleapi", "samplerealm", "Swagger UI");
});
这里重要的变化是.Flow("application")
我也用过.TokenUrl
调用而不是.AuthorizationUrl
这仅取决于您设置的特定授权方案。
我也使用了稍微不同的AssignOAuth2SecurityRequirements
class
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var authorized = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
if (!authorized.Any()) return;
if (operation.security == null)
operation.security = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{
{"oauth2", Enumerable.Empty<string>()}
};
operation.security.Add(oAuthRequirements);
}
}
这应该足以显示身份验证开关。对我来说另一个问题是设置了默认身份验证对话框,因此用户只需选择范围,然后单击授权。就我而言,由于我设置身份验证的方式,这不起作用。我必须在 swagger-oauth.js 脚本中重新编写对话框并将其注入到 SwaggerUI 中。