![](/img/trans.png)
[英]ASP MVC 5 Windows authentication with custom roles and Active Directory
[英]Custom roles in MVC 5 for Active Directory authentication
因此,我创建了一个具有“ Windows身份验证”的测试MVC 5 Web应用程序。 现在,我想基于预定义角色隐藏/显示/允许访问应用程序的不同部分。 我的角色可以硬编码为“管理员”和“用户”。
这意味着我需要一个包含Windows登录名及其角色的表。 现在的问题是,我该如何实现类似于MVC身份已提供的“授权”的功能。 示例[Authorize(Roles="Admin")]
。 我的猜测是,此代码会自动从表AspNetUserRoles中获取登录用户的信息。
我可以手动创建表AspNetUsers,AspNetRoles,AspNetUserRoles吗? 然后用所需的数据填充它们,它将起作用吗? 可以对表AspNetUsers中的密码进行硬编码,因为我不会将其用于登录目的。 请提出建议。
您需要跟踪代码以创建ClaimsIdentity并添加新的Claim: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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.