【问题标题】:Custom roles in MVC 5 for Active Directory authenticationMVC 5 中用于 Active Directory 身份验证的自定义角色
【发布时间】:2016-02-27 05:38:46
【问题描述】:

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

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

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

【问题讨论】:

  • 对不起,这个重复:stackoverflow.com/questions/6043100/…
  • @ataravati ,我实际上想使用 Authorize 而不是您在其他链接中提到的方式。
  • 您不能使用授权,除非您使用 NT 组作为角色。
  • @ataravati 哦!我知道了。感谢您提供信息。

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


【解决方案1】:

您需要将代码跟踪到 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;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多