对Swashbuckle.AspNetCore请求的空授权标头

时间:2018-04-18 20:33:34

标签: asp.net-core http-headers asp.net-core-2.0 asp.net-core-webapi swashbuckle

目前在.net核心的swashbuckle中存在授权标题问题 每个端点上的第一行代码是:

string auth = Request.Headers["Authorization"];

使用邮递员时,一切顺利,但是当从localhost / swagger发出请求时,标题为空 插入断点时,标题为空值 当从端点移除授权时,请求的主体是完整的,一切正常。

在我的services.AddSwaggerGen中,我添加了安全性定义:

   services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "Employee Navigator",
                Description = "Authorization Key: Z29vZEtleQ==",
            });
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme
            {
                Name = "Authorization",
                In = "header",
                Type = "apiKey",
                Description = "Authorization Key: Z29vZEtleQ=="
            });
            c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
            {
                { "Authorization", new[] { "readAccess", "writeAccess" } }
            });

        });

我已更新以下各项,以确保我没有遗漏任何内容: 我的csproj文件包含:

  <ItemGroup>
<Folder Include="wwwroot\" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="2.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="2.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="2.4.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.1.0" />

3 个答案:

答案 0 :(得分:0)

这里的问题是您的安全定义中的名称(“ Bearer” )与添加到您的安全要求中的名称(“ Authorization” )不匹配。对于后台上下文,SwashBuckle中曾经存在一个错误,这意味着它在未定义SecurityRequirement的情况下强制执行授权,因此很多人发现它突然停止为它们工作。 Requirement定义有点笨拙,并导致诸如此类的问题。

如果您更改SecurityRequirement以使其与下面的代码匹配,则它应该起作用:

 services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "Employee Navigator",
            Description = "Authorization Key: Z29vZEtleQ==",
        });
        c.AddSecurityDefinition("Bearer", new ApiKeyScheme
        {
            Name = "Authorization",
            In = "header",
            Type = "apiKey",
            Description = "Authorization Key: Z29vZEtleQ=="
        });
        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new[] { "readAccess", "writeAccess" } }
        });

    });

答案 1 :(得分:0)

首先,你可以像这样使用AddSwaggerGen方法

  services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc(
                "v1",
                new OpenApiInfo
                {
                    Title = "v1",
                    Description = "My Web - API",
                    Version = "V1.0.0"
                });
            // Add security definitions
            var securityScheme = new OpenApiSecurityScheme()
            {
                Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.Http,
                BearerFormat = "JWT",
                Scheme = "bearer"
            };
            c.AddSecurityDefinition("Bearer", securityScheme);
            
            //And Add security requirements globally.  If needs to be unique per operation then use IOperationFilter. 
            c.OperationFilter<AuthResponsesOperationFilter>();
        });

例如 AuthResponsesOperationFilter 可以删除 AllowAnonymous 方法上的授权挂锁图标

AuthResponsesOperationFilter

public class AuthResponsesOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<AuthorizeAttribute>();

        if (authAttributes.Any())
        {
            var securityRequirement = new OpenApiSecurityRequirement()
            {
                {
                    // Put here you own security scheme, this one is an example
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        },
                        Scheme = "Bearer",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"",
                        Type = SecuritySchemeType.ApiKey,
                        BearerFormat = "JWT"
                    },
                    new List<string>()
                }
            };
            
            operation.Security = new List<OpenApiSecurityRequirement> { securityRequirement };
            operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
        }
    }
}

答案 2 :(得分:-1)

如果有人遇到此问题,请找到答案:

我的解决方案可以在这里找到: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/696

有关该主题的更多信息,请访问: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/603