在.NET Core 3.1 WebAPI中使用后备授权策略
我有一个.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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论