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

时间:2016-11-22 18:42:45

标签: authentication asp.net-web-api

我有一个客户端要求使用自定义角色/成员资格架构的基于身份验证的集成解决方案。我最初的计划是使用基于声明的身份验证机制和集成身份验证。但是,我最初的研究并没有提供大量有用的信息。

到目前为止,我有一个ASP.NET(非核心或owin)WebAPI应用程序,它具有基于角度SPA(asp.net)Web应用程序使用的api操作。我试图使用集成身份验证授权api调用。我最初的工作重点是自定义AuthorizationAttribute和ClaimsAuthenticationManager实现。然而,随着我深入研究,我开始遇到自定义ClaimsAuthenticationManager的问题,此时我不确定这是正确的路径。

所以我对你们所有人的问题是,你能否至少给我一些关于如何实现这一目标的想法?我不需要帮助代码的各个部分,只需要弄清楚适当的"堆栈"可以这么说。

唯一真正的要求是WebAPI调用可以被授权,自定义属性传递声明的名称以进行授权,但声明不在AD中,即使它使用的是Windows身份验证,声明本身也来自数据库中。

提前谢谢大家!

2 个答案:

答案 0 :(得分:2)

请看https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

您的方案没有太大区别:

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

简单地说,这可以通过配置web-api来使用Windows身份验证来解决。

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

并将自己的IAuthorizationFilter添加到Web API管道,该管道将检查当前主体(应该设置),然后使用您自己的主体覆盖此主体(即查询db - 获取声明,并使用您的自定义覆盖它通过设置HttpContext.Current.UserThread.CurrentPrincipal来声明主体。 有关如何向WebAPI管道添加过滤器,请查看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( ... );
  }
}

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

答案 1 :(得分:0)

看看这篇文章。当我在解决你所描述的问题时,我发现它非常有用。

https://leastprivilege.com/2015/07/24/simplified-asp-net-and-mvc-6-security-templates/

相关问题