【问题标题】:Web api authentication handler by pass for some scenarioWeb api 身份验证处理程序通过某些场景
【发布时间】:2015-06-24 17:24:15
【问题描述】:

我在 web api 中使用 AuthenticationHandler 实现了基本的身份验证和授权:DelegatingHandler。

所以在调用任何 api 之前,这个处理程序中的代码会被执行,它基本上检查用户是否经过身份验证。

每个 api 调用都会执行此处理程序。现在我的问题是,对于一些 api,如登录或注册等,用户未登录并且我不需要检查用户身份验证,我该如何绕过这个?

【问题讨论】:

    标签: c# authentication asp.net-web-api


    【解决方案1】:

    您不应混淆身份验证和授权。

    基本上,您的AuthenticationHandler 应该验证用户并设置用户身份

    身份验证的重点是说明此用户是谁(经理、出纳员、匿名用户……)。您不应该在这里拒绝请求,这是为了授权。示例代码:

    public class AuthHandler : DelegatingHandler
    {
          protected override async Task<HttpResponseMessage> SendAsync(
                               HttpRequestMessage request,
                               CancellationToken cancellationToken)
          {
               //authenticate with your data storage (user,password), or decrypt the information from request's token (I don't know what approach you're doing)
               // here I hardcode just for demo
    
               //If the user is authenticated (not an anonymous user)
               //create a identity for that user and set the roles for
               //the user. The roles could come from your db or your decrypted token depending on how you implement your code.
               GenericIdentity MyIdentity = new ClaimsIdentity("MyUser");
               String[] MyStringArray = {"Manager", "Teller"};
               GenericPrincipal MyPrincipal = new GenericPrincipal(MyIdentity, MyStringArray);
    
               //Set the authenticated principal here so that we can do authorization later.
               Thread.CurrentPrincipal = MyPrincipal;
               if (HttpContext.Current != null)
                   HttpContext.Current.User = MyPrincipal;
               return await base.SendAsync(request, cancellationToken);
          }
    }
    

    授权发生在身份验证之后,以验证用户是否有权访问某个功能。这可以通过应用AuthorizeAttribute来实现:

    • 关于操作方法。
    • 在控制器上。 所有操作方法都要求用户匿名。您可以通过应用 AllowAnonymousAttribute 在每个操作方法中覆盖它
    • 通过将AuthorizeAttribute 添加到应用程序过滤器集合来全局。对于特定的操作方法,您可以使用与 AllowAnonymousAttribute 相同的技术。从链接中提取的示例代码:

    在你的情况下,你可以:

    • AuthorizeAttribute 全局添加到您的应用程序过滤器集合中。
    • 根据经过身份验证的用户在AuthHandler 中设置身份。
    • 在您的登录、注册操作方法上应用AllowAnonymousAttribute

    旁注:当今最突出的授权方法是claims based security。如果你有时间,你应该花一些时间来调查一下。基本上,这个想法是相似的,只是我们使用声明而不是角色来进行授权。

    使用基于 web api 的声明,您可以继承 ClaimsAuthorizationManager 以通过覆盖 CheckAccess 方法来实现您的授权规则。

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多