在.NET Core 3.1 WebAPI中使用后备授权策略

发布于 2025-02-13 15:21:27 字数 519 浏览 1 评论 0原文

我有一个.NET Core 3.1 WebAPI,我计划在其中使用后备授权策略作为定义默认授权的机制,只要控制器或路由不明确定义授权策略或允许匿名策略。这对API本身效果很好。但是我遇到的一个问题是Swagger UI。

由于后备策略将应用于API上的每条路线,因此当我尝试访问Swagger UI时,我直接遇到401错误。在.NET 5及更高版本中,授权HandLercontext具有httpContext类型的资源属性。因此,使用httpcontext,我可以检查Swaggerui路径的路由路径和旁路授权。但是在.NET Core 3.1中,此资源属性始终为null。因此,我无法弄清楚如何允许匿名访问Swaggerui,以便用户至少可以浏览API文档。

在Swagger UI注册中,我还使用appendauthorizetosummaryoperationFilter并添加SecurityDefinition,如果他们想尝试API,它将迫使用户通过授权标头。但是,仅仅用于浏览文档,我不想应用任何授权。关于如何对.NET Core 3.1做到这一点的任何建议?

谢谢!

I have a .Net Core 3.1 WebApi where I am planning to use Fallback Authorization policy as a mechanism to define default authorization, whenever a controller or route does not explicitly define Authorize policy or Allow Anonymous policy. This works well for the API itself. But one problem that I run into is the Swagger UI.

Since the fallback policy gets applied to every route on the API, I get 401 error directly when I try to access Swagger UI. In .Net 5 and above, the AuthorizationHandlerContext has a resource property which is of type HttpContext. So using httpcontext, I can check for the route path and bypass Authorization for the SwaggerUI path. But in .Net Core 3.1, this resource property is always null. So I am unable to figure out how to allow anonymous access to SwaggerUI so that users can atleast browse the API documetation.

In Swagger UI registration, I am also using AppendAuthorizeToSummaryOperationFilter and AddSecurityDefinition that will force user to pass the Authorization Header, if they want to try out the API. But just for browsing the docs, I dont want apply any authorization. Any suggestions on how this can be done for .Net Core 3.1?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文