某些场景通过web api身份验证处理程序

时间:2015-04-17 17:57:28

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

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

因此,在调用任何api之前,会执行此处理程序中的代码,该代码基本上会检查用户是否经过身份验证。

为每个api调用执行此处理程序。现在我的问题是,对于少数api,如登录或注册等,用户没有登录,我不需要检查用户身份验证,我怎么能通过这个。

请帮忙

1 个答案:

答案 0 :(得分: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,您可以通过覆盖CheckAccess方法将ClaimsAuthorizationManager子类化为实现授权规则。