【问题标题】:How to setup Swashbuckle.AspNetCore and Oauth2如何设置 Swashbuckle.AspNetCore 和 Oauth2
【发布时间】:2019-11-15 11:32:40
【问题描述】:

我正试图找出我哪里出错了。

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new Info { Title = "MySite API", Version = "v1" });
    options.OperationFilter<AuthorizeCheckOperationFilter>();
    options.OperationFilter<AddSwaggerHeadersOperationFilter>();
    options.AddSecurityDefinition("oauth2", new OAuth2Scheme
    {
        Type = "oauth2",
        Flow = "implicit",
        AuthorizationUrl = "authorization url",
        TokenUrl = "token url",
        Scopes = new Dictionary<string, string>()
        {
            { "scope", "Scope" }
        }
    });
});


//Configure Method
app.UseSwagger();

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "MySite API V1");
    options.OAuthClientId("MyClientId");
    options.OAuthAppName("Swagger Api Calls");
    //c.RoutePrefix = string.Empty;
});

//AuthorizeCheckOperationFilter
internal class AuthorizeCheckOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.TryGetMethodInfo(out var methodInfo))
        {
            var attributes = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(true);
            if (attributes.OfType<AuthorizeAttribute>().Any())
            {
                operation.Responses.Add("401", new Response { Description = "Unauthorized" });
                operation.Responses.Add("403", new Response { Description = "Forbidden" });

                operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
                operation.Security.Add(new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", new [] { "api1" } }
                });
            }
        }
    }
}

//Extra field
internal class AddSwaggerHeadersOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            operation.Parameters = new List<IParameter>();

        operation.Parameters.Add(new NonBodyParameter
        {
            Name = "SomeField",
            In = "header",
            Type = "string",
            Required = true,
            Default = "some value"
        });
    }
}

现在,当我打开 swagger 页面时,我得到了 Authorize 按钮,我单击该按钮,当我在那里填写详细信息时,我被重定向到我的身份网站,该网站将我登录并重定向回 swagger。 Swagger 然后说授权,好像一切都很好。

然后我尝试使用需要传递 Bearer 令牌的 API,但它没有传递它。我没有在标题中看到它,而且我在身份网站的日志中没有看到任何内容。

知道为什么或如何解决这个问题吗?我正在使用 Swashbuckle.AspNetCore 4.1 包。

【问题讨论】:

    标签: oauth-2.0 asp.net-core-mvc swagger swagger-ui swashbuckle


    【解决方案1】:

    你可以加DocumentFilter

    public class SecurityRequirementsDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument document, DocumentFilterContext context)
        {
            document.Security = new List<IDictionary<string, IEnumerable<string>>>()
            {
                new Dictionary<string, IEnumerable<string>>()
                {
                    { "oauth2", new string[]{ "openid", "profile", "email" } },
                }
            };
        }
    }
    

    然后在AddSwaggerGen函数中注册过滤器:

    options.DocumentFilter<SecurityRequirementsDocumentFilter>();
    

    参考:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/603#issuecomment-368487641

    我用您的代码示例进行了测试,它按预期工作:

    【讨论】:

    • 这已经奏效了。看我以为我的操作过滤器应该这样做。我应该将我的逻辑从操作过滤器移动到文档吗?
    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2023-04-05
    相关资源
    最近更新 更多