且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于声明的身份验证,具有活动目录,无ADFS

更新时间:2023-12-03 11:34:46

查看您的情况没有太大不同:

Your scenario isn't much different:

  • 您正在使用AD进行身份验证
  • 您正在使用数据库进行授权

简单地说,可以通过将web-api配置为使用Windows身份验证来解决此问题.

Simply put this can be addressed by configuring web-api to use windows authentication.

<system.web>
   <authentication mode="Windows" />
</system.web>

并将您自己的IAuthorizationFilter添加到Web API管道中,它将检查当前主体(应设置),然后用您自己的主体(即查询数据库-获取声明,并用您的自定义声明主体覆盖它)通过设置HttpContext.Current.UserThread.CurrentPrincipal). 有关如何将过滤器添加到WebAPI管道的信息,请查看如何添加全局ASP.Net Web Api筛选器?

And add your own IAuthorizationFilter to Web API pipeline, that will check current principal (should be set), and then override this principal with your own (i.e. query db - get claims, and override it with your custom claims principal by setting HttpContext.Current.User and Thread.CurrentPrincipal). For how to add filter to WebAPI pipe line check out How to add global ASP.Net Web Api Filters?

public class CustomAuthenticationFilter : IAuthenticationFilter {
  public bool AllowMultiple { get { return true; } }
  public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) {
    var windowsPrincipal = context.Principal as WindowsPrincipal;
    if (windowsPrincipal != null) {
      var name = windowsPrincipal.Identity.Name;
      // TODO: fetch claims from db (i guess based on name)
      var identity = new ClaimsIdentity(windowsPrincipal.Identity);
      identity.AddClaim(new Claim("db-crazy-claim", "db-value"));
      var claimsPrincipal = new ClaimsPrincipal(identity);
      // here is the punchline - we're replacing original windows principal 
      // with our own claims principal
      context.Principal = claimsPrincipal;
    }

    return Task.FromResult(0);
  }

  public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) {
    return Task.FromResult(0);
  }
}

public static class WebApiConfig {
  public static void Register(HttpConfiguration config) {
    config.Filters.Add(new CustomAuthenticationFilter());

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute( ... );
  }
}

也不需要自定义授权属性-使用默认属性-每个人都可以理解它,并使您的代码更具可读性.

Also there is no need for custom authorization attribute - use default one - its understood by everyone, and makes your code more readable.