简体   繁体   English

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

[英]Custom roles in MVC 5 for Active Directory authentication

So I created a test MVC 5 web application that has "Windows Authentication". 因此,我创建了一个具有“ Windows身份验证”的测试MVC 5 Web应用程序。 Now I want to hide/show/allow access to different part of application based on predefined roles. 现在,我想基于预定义角色隐藏/显示/允许访问应用程序的不同部分。 My roles can be hard coded as "Admin" and "User". 我的角色可以硬编码为“管理员”和“用户”。

That means I need to have a table that holds windows login name and their role. 这意味着我需要一个包含Windows登录名及其角色的表。 Now the question is how can I achive something similar to "Authorize" that MVC identity already provided. 现在的问题是,我该如何实现类似于MVC身份已提供的“授权”的功能。 Example [Authorize(Roles="Admin")] . 示例[Authorize(Roles="Admin")] My guess is that this code automatically get info from table AspNetUserRoles for logged in user. 我的猜测是,此代码会自动从表AspNetUserRoles中获取登录用户的信息。

Can I manually create tables AspNetUsers, AspNetRoles, AspNetUserRoles. 我可以手动创建表AspNetUsers,AspNetRoles,AspNetUserRoles吗? Then fill them with required data and it will work ? 然后用所需的数据填充它们,它将起作用吗? Passwords in table AspNetUsers can hardcoded because I will not be using it for login purpose. 可以对表AspNetUsers中的密码进行硬编码,因为我不会将其用于登录目的。 Please suggest. 请提出建议。

what you need is to trace your code to ClaimsIdentity creation and add a new Claim: ClaimTypes.Role 您需要跟踪代码以创建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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM