Ronin
Ronin

Reputation: 7950

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:

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

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();
}

Upvotes: 1

Views: 1378

Answers (1)

DavidG
DavidG

Reputation: 118937

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);

Upvotes: 4

Related Questions