简体   繁体   中英

adding roles in asp.net mvc 4 application using identity provider

I have a ASP.NET MVC 4 Web Application "APP1" which has Entity Framework implemented using the DB First approach. I'm using the automatically generated Account - model , - views and - controller for Authentication.

So far, everything seems fine. I can add new users and log in. My question now is: How can I add roles to my users? I basically only need 1 role.

Additional Information

I made 2 small modifications:

  • I extended the AccountModel with an additional EmailAdress property
  • I changed the ConnectionString Property so my EF SQL Server Instance is being used instead of a LocalDb

The following tables were automatically generated at my EF SQL Server DB

  • dbo.UserProfile
  • dbo.webpages_Membership
  • dbo.webpages_OAuthMembership
  • dbo.webpages_Roles
  • dbo.webpages_UsersInRoles

UPDATE

I ended up with creating them manually. See my TSQL Code bellow

INSERT INTO webpages_Roles (RoleName) VALUES ('canEdit')
INSERT INTO webpages_UsersInRoles (UserId, RoleId) VALUES (2, 1)

To make an ActionResult available only for authorized persons with a specific role, I decorated them as follow:

[Authorize(Roles = "canEdit")]
public ActionResult Index()
{
    // return View();
}

For Identity v1, the code is:

var username = "Fred";
var roleName = "Administrator";
Roles.AddUserToRole(username, roleName);

If you are using Identity v2 (assuming you have your userManager object):

var username = "Fred";
var roleName = "Administrator";
var user = await userManager.FindByNameAsync(username);
userManager.AddToRole(user.Id, roleName);

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