如何在Swagger-Net中为Bearer身份验证指定凭据

时间:2019-01-27 09:18:58

标签: .net swagger

我正在从Swashbuckle迁移到Swagger-Net,并且需要指定用户凭据的帮助以获取承载令牌并对其进行身份验证。

如果我将明确指定承载令牌,那么一切都可以正常工作,但是我想要一种方法来指定用户名,密码和ClienId,然后获取承载令牌并将其包含在所有请求中。

在Swashbuckle中,我可以使用此article实现它。除了上面的文章,还有其他方法可以使其与Swagger-net一起使用吗?

更新:我尝试使用OAuth,可以进行授权,但不向每个请求添加承载令牌。此外,如果我在方法上按auth,则可用授权为空。怎么了?

httpConfiguration
     .EnableSwagger(c =>
         {
            c.OAuth2("oauth2")
                .Flow("password")
                .TokenUrl("/token");

             c.OperationFilter<AssignOAuth2SecurityRequirements>();
         });
     .EnableSwaggerUi(c =>
         {
             c.EnableOAuth2Support("test-client-id", "test-realm", "Swagger UI");
         });

1 个答案:

答案 0 :(得分:0)

最后,我成功了。问题出在错误的AssignOAuth2SecurityRequirements过滤器中:我指定了Bearer而不是oauth2安全性

public class AssignOAuth2SecurityRequirements : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            // Correspond each "Authorize" role to an oauth2 scope
            var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
                .Select(filterInfo => filterInfo.Instance)
                .OfType<AuthorizeAttribute>()
                .SelectMany(attr => attr.Roles.Split(','))
                .Distinct();

            if (scopes.Any())
            {
                if (operation.security == null)
                    operation.security = new List<IDictionary<string, IEnumerable<string>>>();

                var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", scopes }
                };

                operation.security.Add(oAuthRequirements);
            }
        }
    }