C# LDAP AD 认证,使用 Job Title 进行授权

C# LDAP AD Authentication, use Job Title for authorization

我在网上看到很多关于如何使用Role-based授权的文章和示例代码,但是找不到任何与title-based授权相关的内容。

我在 class 中有以下内容用于 AD 身份验证:

 protected ClaimsIdentity CreateIdentity(UserPrincipalExtended userPrincipal)
    {
        var identity = new ClaimsIdentity(MyAuthentication.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType,
            ClaimsIdentity.DefaultRoleClaimType);
        identity.AddClaim(new Claim(
            "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
            "Active Directory"));
        identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.Name));
        identity.AddClaim(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName ?? string.Empty));
        identity.AddClaim(new Claim(ClaimTypes.Surname, userPrincipal.Surname ?? string.Empty));
        identity.AddClaim(new Claim(userPrincipal.Title, userPrincipal.Title ?? string.Empty));
        identity.AddClaim(new Claim(userPrincipal.Department, userPrincipal.Department ?? string.Empty));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
        if (!string.IsNullOrEmpty(userPrincipal.EmailAddress))
            identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));

        var claims = new List<Claim>();
        var dirEntry = (DirectoryEntry) userPrincipal.GetUnderlyingObject();
        foreach (string groupDN in dirEntry.Properties["memberOf"])
        {
            var parts = groupDN.Replace("CN=", "").Split(',');
            claims.Add(new Claim(ClaimTypes.Role, parts[0]));
        }


        if (claims.Count > 0)
            identity.AddClaims(claims);


        var title = dirEntry.Properties["title"].Value.ToString();
        return identity;
    }

这工作正常,我可以看到从 Active Directory 检索到的正确职位和部门。显然我使用的是扩展的 UserPrincipal,因为职位和部门不是标准 UserPrincipal 的一部分。

我的问题是我无法将职位和部门值传递给我的 Controller 进行授权。

在 HomeController 中,我使用以下方法获取经过身份验证的用户的信息:

var firstname = System.Web.HttpContext.Current.User.GetFirstname();
var lastname = System.Web.HttpContext.Current.User.GetLastname();
var email = System.Web.HttpContext.Current.User.GetEmail();
var uid = System.Web.HttpContext.Current.User.GetUserID();

显然这使用了标准 IPrincipal,它不包含标题和部门的规定。

有没有一种简单的方法可以将标题和部门参数传递给控制器​​?是否可以将标题用于授权访问而不是角色?

提前致谢

我遇到了类似的挑战,并通过使用(在您的案例中)标题和部门作为角色解决了这个问题。 这允许使用所有 out-of-the-box 基于角色的授权功能。

if (userPrinciple.Title != null)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, userPrincipal.Title));
}

if (userPrincipal.Department != null)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, userPrincipal.Department));
}

如果角色是部门特定的,您可以将两者结合起来。

identity.AddClaim(new Claim(ClaimTypes.Role, $"{userPrincipal.Department}.{userPrincipal.Title}));