使用Windows身份验证在OWIN管道中添加声明

时间:2014-11-06 15:40:57

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

我试图探索在OWIN管道中如何向用户添加其他声明。 我知道我可以在登录阶段或其他一些点上执行此操作,可能在Application_PostAuthenticate的{​​{1}}部分,因为我没有Global.asax部分(& #39;是一个Windows身份验证应用程序),但我想知道在OWIN管道中是否可行甚至更好。

我的想法来自于OWIN在管道中也有一个Login阶段。所以我尝试了这个:

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();
});

但我新增的索赔没有出现。有什么想法吗?

我知道"一些"无论如何都需要在应用程序级别添加声明(角色来自数据库和其他东西),但我想探索直接从OWIN管道添加某些声明。

1 个答案:

答案 0 :(得分:3)

我在我的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

起作用了