首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用OpenAPI操作筛选器向需要身份验证的控制器端点添加安全性要求

使用OpenAPI操作筛选器向需要身份验证的控制器端点添加安全性要求
EN

Stack Overflow用户
提问于 2020-03-15 15:02:58
回答 1查看 3.1K关注 0票数 2

我试图通过向需要身份验证的端点添加安全性要求来改进我的项目openapi定义。

如果端点是带有[Authorize]装饰器的类的方法,并且缺少[AllowAnonymous]装饰器,则需要身份验证。

我试图在此基础上使用IOperationFilter添加安全性要求,但我很难找到过滤器描述符--我无法找到任何关于这些文件是如何工作的文档。

这是我基于另一个StackOverflow线程的当前筛选器:

代码语言:javascript
运行
复制
using Microsoft.AspNetCore.Http; 
using Microsoft.AspNetCore.Mvc.Authorization; 
using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.Swagger; 
using Swashbuckle.AspNetCore.SwaggerGen; 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;

namespace OpenData.Filters {
    public class AddAuthHeaderOperationFilter : IOperationFilter
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
            var allowAnonymous = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);

            if (/*isAuthorized && */!allowAnonymous)
            {
                operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
                operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
                //Add JWT bearer type
                operation.Security.Add(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            },
                            Scheme = "Bearer",
                            Name = "Bearer",
                            In = ParameterLocation.Header,

                        },
                        new List<string>()
                    }
                });
            }
        }
    }
}

我的问题是filterDescriptor部分。如何使用它来检测我当前应用的是一个带有[Authorize]装饰器的类的方法,如果是,如果它有一个[AllowAnonymous]装饰器?我可能也滥用了术语,这是一种我想检测到的方法:

代码语言:javascript
运行
复制
    [Authorize]
    [Route("/api/[controller]")]
    public class CommentController : Controller
    {

        [AllowAnonymous]
        [HttpGet("metadata/{metadataUuid}")]
        public async Task<IActionResult> GetCommentsForMetadataAsync(Guid metadataUuid)
        {
            // ...
        }

对此进行研究是一件很痛苦的事情,在web上似乎没有任何关于这个API的容易获得的文档,我也没有找到这个版本的dotnetcore/swagger的任何例子。

我的版本:

3.1

  • Swashbuckle.AspNetCore
  • .netcore 5.0.0
EN

回答 1

Stack Overflow用户

发布于 2020-03-16 08:47:27

一个具有授权装饰器的类的方法,如果它(一个动作)有一个AllowAnonymous装饰器?我可能也在滥用术语

为了实现上述要求,您可以尝试以下代码片段:

代码语言:javascript
运行
复制
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
    var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
        .Union(context.MethodInfo.GetCustomAttributes(true))
        .OfType<AuthorizeAttribute>();

    var allowAnonymousAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
        .Union(context.MethodInfo.GetCustomAttributes(true))
        .OfType<AllowAnonymousAttribute>();


    if (authAttributes.Any() && !allowAnonymousAttributes.Any())
    {
        operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
        operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
    }
        //...

}

有关操作过滤器的更多信息,请查看以下文档:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#operation-filters

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60694260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档