Reputation: 959
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.
Upvotes: 1
Views: 1530
Reputation: 149
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;
}
Upvotes: 0