gpt4 book ai didi

c# - MVC 5 中的身份验证过滤器

转载 作者:可可西里 更新时间:2023-11-01 07:45:11 25 4
gpt4 key购买 nike

来自 Release Notes 的身份验证过滤器页

Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. Authentication filters process credentials in the request and provide a corresponding principal. Authentication filters can also add authentication challenges in response to unauthorized requests.

有人可以提供这个的实际用途吗?我可以在哪里使用这个 AuthenticationFilters?

早些时候,我通过编写自己的 CustomAttribute: FilterAttribute, IAuthorizationFilter 和实现 public void OnAuthorization(AuthorizationContext filterContext) 来管理操作/ Controller 的访问控制列表。可以在这里使用这个 AuthenticationFilter 吗?

最佳答案

正如文档所说,自定义身份验证过滤器为每个操作、每个 Controller 或全局提供身份验证。

一个示例用途是更改少数选定 Controller 的身份验证。例如,假设您的整个站点使用表单例份验证,其中主体取自表单 cookie。

但是,您有一个选定的 Controller 充当 OAuth2 资源服务器,其中请求来自服务提供商(服务器)并且没有表单 cookie,而是由服务提供商服务器提供 OAuth2 访问 token 。

这是自定义身份验证过滤器发挥作用的地方 - 它的任务是仅在当前请求的生命周期内将 token 转换为主体,仅适用于充当资源服务器端点的唯一 Controller 。您不希望整个站点接受 OAuth2 token ,而是一个特定的 Controller 。

引入认证过滤器的原因是为了将认证与授权分开,其中:

  • 认证是为当前请求建立主体
  • 授权是验证当前委托(delegate)人是否被允许执行当前请求

在引入身份验证过滤器之前,这并没有明确区分。就我个人而言,我曾经为此使用授权过滤器,但是按照这个特定的顺序(首先是身份验证,然后是授权)有两个单独的过滤器层更干净。

关于c# - MVC 5 中的身份验证过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com