MVC 5中的自定义角色,用于Active Directory身份验证

时间:2015-11-24 16:53:56

标签: asp.net-mvc asp.net-mvc-5 active-directory

所以我创建了一个测试MVC 5 Web应用程序,它具有" Windows身份验证"。现在我想隐藏/显示/允许基于预定义角色访问应用程序的不同部分。我的角色可以硬编码为" Admin"和"用户"。

这意味着我需要一个包含Windows登录名及其角色的表。现在的问题是我怎样才能实现类似于"授权"已经提供了MVC身份。示例[Authorize(Roles="Admin")]。我猜这个代码会自动从表AspNetUserRoles获取登录用户的信息。

我可以手动创建表AspNetUsers,AspNetRoles,AspNetUserRoles。然后用必要的数据填充它们,它会工作吗?表AspNetUsers中的密码可以硬编码,因为我不会将其用于登录目的。请建议。

1 个答案:

答案 0 :(得分:0)

您需要的是将您的代码跟踪到ClaimsIdentity创建并添加新的声明:ClaimTypes.Role

private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
            {
            var identity = new ClaimsIdentity(
                Startup.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.SamAccountName));

            if (userPrincipal.SamAccountName == "flastname" 
                || userPrincipal.Name == "FirstName LastName")
                {
                    // this will add role to the user, you can add as many as you want
                    identity.AddClaim(new Claim(ClaimTypes.Role, "Administrator"));
                }

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
            if (!String.IsNullOrEmpty(userPrincipal.EmailAddress))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));
            }

            // add your own claims if you need to add more information stored on the cookie

            return identity;
        }