【问题标题】:How to specify credentials for Bearer auth in Swagger-Net如何在 Swagger-Net 中为承载身份验证指定凭据
【发布时间】:2019-01-27 09:18:57
【问题描述】:

我正在从 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");
         });

【问题讨论】:

标签: .net swagger


【解决方案1】:

最后,我让它工作了。问题出在错误的 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);
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2021-10-07
    • 2015-06-01
    • 1970-01-01
    相关资源
    最近更新 更多