【问题标题】:Apply claims-based authorization policy to Swagger UI in .Net Core 3.1将基于声明的授权策略应用于 .Net Core 3.1 中的 Swagger UI
【发布时间】:2021-02-26 20:38:29
【问题描述】:

我使用 ASP.Net Core 3.1 创建了一个 API,并使用 Swashbuckle 在站点的根目录添加了 Swagger UI。也许这是一个微不足道的问题,但我希望 Swagger UI 只能由授权用户访问(即不公开)。我已经阅读了很多关于 Swagger 如何处理 API 授权方案的文章,但没有关于 Swagger UI 本身的文章。特别是我需要通过一些[Authorize(Policy="MyCustomPolicy")] 属性或等效属性来限制对它创建的静态文件的访问,因此只有在其身份中具有特定声明的用户才能访问 UI。只有在 Swagger UI 上才需要此条件,因为 API 本身已经通过 Bearer 身份验证进行了访问控制,而且效果很好。

如何将此声明要求添加到 Swagger UI?

这就是我添加 Swagger 服务的方式:

// Register the Swagger Generator service. This service is responsible for genrating Swagger Documents.
// Note: Add this service at the end after AddMvc() or AddMvcCore().
services.AddSwaggerGen(c =>
{
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "MySystem API",
            Version = "v1",
            Description = "API for MySystem.",
            Contact = new OpenApiContact
            {
                Name = "MyCompany S.A.",
                Email = string.Empty,
                Url = new System.Uri("https://contoso.com/"),
            },
        });

        var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "MySystem.Web.xml");
        c.IncludeXmlComments(filePath);

        c.CustomSchemaIds(x => x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? x.Name);
    });

这就是我将 Swagger 添加到构建器的方式:

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MySystem API v1");

        // To serve SwaggerUI at application's root page, set the RoutePrefix property to an empty string.
        c.RoutePrefix = string.Empty;
    });

提前致谢。

【问题讨论】:

    标签: swagger swashbuckle.aspnetcore


    【解决方案1】:

    事实证明这是here的回答。我只需要补充:

    app.UseAuthentication(); // before UseAuthorization()
    
    // Original answer
    app.UseAuthorization(); // before the middleware
    ...
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 2020-02-16
      • 1970-01-01
      • 2017-06-08
      • 2021-10-23
      • 2019-12-16
      • 2021-04-13
      • 1970-01-01
      相关资源
      最近更新 更多