使用Windows身份验证时如何保留自定义声明

时间:2018-10-16 08:31:52

标签: c# asp.net-mvc authentication

使用Windows身份验证时,我试图向我的MVC应用添加声明,但是声明在请求之间不存在。

有关如何执行此操作的任何建议?我在global.asax的Application_AuthorizeRequest中添加了声明,并在控制器中读取了该值。

Global.asax:

protected void Application_AuthorizeRequest()
{
    var claimsPrincipal = User as ClaimsPrincipal;
    var claimsIdentity = User.Identity as ClaimsIdentity;
    if (!claimsPrincipal.Claims.Where(x => x.Type == "IsSpecial").Any()) \\ALWAYS TRUE!
    {
        var domain = User.Identity.Name.Split('\\')[0];

        using (var ctx = new PrincipalContext(ContextType.Domain, domain))
        using (var user = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name))
        {
            if (user != null)
            {
                var groups = user.GetGroups()
                   .Select(x => x.SamAccountName);

                if (groups.Contains("Special User")
                {
                    claimsIdentity.AddClaim(new Claim("IsSpecial", "Yes"));
                }

控制器:

var claimsPrincipal = User as ClaimsPrincipal;
    var isSpecial = claimsPrincipal.Claims.Where(x => x.Type == "IsSpecial").First().Value;

1 个答案:

答案 0 :(得分:1)

这就是它的工作方式。尽管身份验证方法之间的确切方法有所不同,但仍会为每个请求始终重新创建用户的身份。

启用Windows身份验证基本上只是意味着在浏览器发送票证/用户名/密码时自动为您设置用户名。

无论您使用Cookie,承载令牌还是Windows身份验证,并且无论是将声明存储在AD,数据库还是令牌中,仍然需要在每个请求的某个时间点添加声明。 < / p>