简体   繁体   中英

Custom roles in MVC 5 for Active Directory authentication

So I created a test MVC 5 web application that has "Windows Authentication". 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. Now the question is how can I achive something similar to "Authorize" that MVC identity already provided. Example [Authorize(Roles="Admin")] . My guess is that this code automatically get info from table AspNetUserRoles for logged in user.

Can I manually create tables 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. Please suggest.

what you need is to trace your code to ClaimsIdentity creation and add a new 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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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