【问题标题】:Swagger Asp.Net Core: Security for selected functions onlySwagger Asp.Net Core:仅限选定功能的安全性
【发布时间】:2022-11-14 20:51:51
【问题描述】:

我想用 ASP.net Core 创建一个 WebAPI。 API 受授权保护。但并非所有功能都受到保护! 我怎样才能用 Swagger 实现这一点?

这是我的 Swagger 设置:

[...]

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please enter a valid token",
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type=ReferenceType.SecurityScheme,
                    Id="Bearer"
                }
            },
            new string[]{}
        }
    });
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

[...]

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = "swagger/index.html";
    });
}

[...]

函数如下所示:

/// <summary>
    /// Registriert einen neuen User
    /// </summary>
    /// <returns></returns>
    /// <response code="200">...</response>
    /// <response code="400">...</response>
    [HttpPost]
    [Route("Register")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    public async Task<IActionResult> Register([FromBody] UserRegistrationDto user)
    { [...] }

在 Swagger 中,它看起来像这样:

锁表示此功能可能/需要授权。我想卸下锁。但仅限于此功能。我怎么能在 C# 中做到这一点?

(swagger 文件是自动生成的,我不想修改导出的 .yaml 或 .json 文件。所以我需要一个直接在 c# 代码或 swagger 配置中工作的解决方案。)

【问题讨论】:

  • 如果注册不需要身份验证,为什么[ProducesResponseType(StatusCodes.Status401Unauthorized)]?您可以尝试添加[AllowAnonymous] 属性吗?

标签: c# asp.net-core-webapi swagger-ui openapi swashbuckle.aspnetcore


【解决方案1】:

您应该为此添加 Operation 过滤器,并在方法中添加 AllowAnonymous

public class BasicAuthOperationsFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var noAuthRequired = context.ApiDescription.CustomAttributes().Any(attr => attr.GetType() == typeof(AllowAnonymousAttribute));

        if (noAuthRequired) return;

        operation.Security = new List<OpenApiSecurityRequirement>
        {
            new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "basic"
                        }
                    },
                    new List<string>()
                }
            }
        };
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 2018-03-20
    • 2018-11-11
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多