【问题标题】:Add Claims during the OWIN pipeline with Windows Authentication在使用 Windows 身份验证的 OWIN 管道期间添加声明
【发布时间】:2014-11-06 15:40:57
【问题描述】:

我正在尝试探索如何在 OWIN 管道期间向用户添加其他声明。 我知道我可以在登录阶段或其他一些时间点执行此操作,可能在Global.asaxApplication_PostAuthenticate 部分,因为我没有Login 部分(这是一个Windows 身份验证应用程序),但我想知道在 OWIN 管道中是否有可能甚至更好。

我的想法来自这样一个事实,即 OWIN 也有一个 PostAuthenticate 阶段正在筹备中。所以我尝试了这个:

app.Use((context, next) =>
{
    var user = context.Authentication.User.Identity as ClaimsIdentity;
    if (user != null)
    {
        user.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
        user.AddClaim(new Claim(ClaimTypes.GivenName, "Mr. Tallmaris"));
    }
    return next.Invoke();
});

通过断点,我可以看到用户是正确的用户并且添加了声明,但在我的视图中,我有这样的内容:

<ul>
    @foreach (var claim in ClaimsPrincipal.Current.Claims)
    {
        <li>@claim.Type - @claim.Value</li>
    }
</ul>

但是我新添加的声明没有出现。有什么想法吗?

我知道无论如何都需要在应用程序级别添加“一些”声明(来自 DB 和其他事物的角色),但我想探索直接从 OWIN 管道添加某些声明。

【问题讨论】:

    标签: asp.net-mvc-5 windows-authentication owin


    【解决方案1】:

    我在我的 asp.net 应用程序中使用此原则将 groupid 声明转换为角色声明。

    app.Use((context, func) => {
      var claimsIdentity = context.Authentication.User.Identity as ClaimsIdentity;
      if (claimsIdentity != null) {
        var claimsToAdd = new List<Claim>();
        //check if we have any groupsid claims, add these as role claims
        foreach (var claim in claimsIdentity.Claims) {
          if (claim.Type == ClaimTypes.GroupSid) {
            claimsToAdd.Add(new Claim(ClaimTypes.Role,
              new SecurityIdentifier(claim.Value)
                .Translate(typeof(NTAccount)).ToString()));
          }
        }
        if (claimsToAdd.Count > 0) {
          claimsIdentity.AddClaims(claimsToAdd);
        }
      }
      return func.Invoke();
    });
    

    这适用于我使用 Microsoft.Owin v3.0.0.0

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 2014-09-29
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2016-10-22
      • 2015-07-18
      • 1970-01-01
      相关资源
      最近更新 更多