为了账号安全,请及时绑定邮箱和手机立即绑定

C# LDAP AD 认证,使用职位进行授权

C# LDAP AD 认证,使用职位进行授权

C#
忽然笑 2021-07-04 13:52:32
我在网上看了很多关于如何使用基于角色的授权的文章和示例代码,但找不到任何与基于标题的授权相关的内容。我在 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 的一部分。我的问题是我无法将标题和部门值传递给我的控制器进行授权。在 HomeController 中,我使用以下命令获取经过身份验证的用户的信息:显然,这使用了不包含头衔和部门规定的标准 IPrincipal。有没有一种简单的方法可以将标题和部门参数传递给控制器?是否可以将标题用于授权访问而不是角色?
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

我遇到了类似的挑战,并通过使用(在您的情况下)职位和部门作为角色来解决它。这允许使用所有现成的基于角色的授权功能。


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


查看完整回答
反对 回复 2021-07-10
  • 1 回答
  • 0 关注
  • 205 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信