Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Roles in user identity in MVC 5

I want to use asp.net useridentity in mvc 5, I do these steps:

1) create a mvc project.

2) create my own database and change the connectionstring in web.config form: to:

3) I run the project and create a new user to add related table to my database.

4) I wanted to add a role to a user after registration a user like this code in accountControler:

public async Task<ActionResult> Register(RegisterViewModel model)
  {
     if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //******************* Add Role To User  **************
                if (!Roles.RoleExists("Member"))
                    Roles.CreateRole("Member");
                Roles.AddUserToRole(model.Email, "Member");
                //****************************************************

                await SignInAsync(user, isPersistent: false);
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

5) I add

<roleManager enabled="true">

into:

<system.web></system.web>

when I create a new user my user register well but user not add to the role, and when I do this VS Create a new database in App_Data with name "ASPNETDB.MDF". so I found a new article that explain about Role Provider Settings in web.config and:

6) I add

<roleManager enabled="true">
  <providers>
    <clear/>
    <add name="AspNetSqlRoleProvider" connectionStringName="DefaultConnection" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
</roleManager>

into :

<system.web></system.web>

but when I want to register new user I found this Error:

Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

Now I think my problem is when I do step 3 it will not completely create the user identity database and stored procedure! Am I using role true for MVC 5 ? Please help me to solve this problem!

like image 985
Mostafa Azarirad Avatar asked Oct 16 '14 08:10

Mostafa Azarirad


People also ask

How will you implement role based authorization in MVC 5?

Choose MVC5 Controller with views, using Entity Framework and click "Add". After clicking on "Add", another window will appear. Choose Model Class and data context class and click "Add". The EmployeesController will be added under the Controllers folder with respective views.

How do I get user role in .NET core identity?

Show activity on this post. var user = await _userManager. FindByIdAsync(UserId); var roles = await _userManager. GetRolesAsync(user); return OK(new { User = user, Roles = roles });


1 Answers

When you write

 !Roles.RoleExists("Member") 

you are not using ASP.NET Identity! instead, you should use ApplicationRole so it extends the IdentityRole class

In addition, you don't need to tell the AspNetSqlRoleProvider in your config file. Asp.Net Identity is something different. In Asp.Net Identity there is a class named ApplicationRoleManager in the App_Start folder.

You should not use Asp.Net Identity as if it was the old simple membership.

Alternatively, check the beta(which means things may change) version of Identity to learn more on how to do in Identity.

Here is how to start :

  • Create a new project : Choose Empty template (Not MVC not WebForm)
  • Install the Asp.Net identity sample via nuget

    PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre
    
  • edit namespace to match your old project namespace
  • If you want to copy some folders from your old project to the new project, copy your (Controllers, Views,... ) not the config files.

Here you can create roles as follows:

            var role = new IdentityRole("roleName");
            var roleresult = await RoleManager.CreateAsync(role);

and to create and add a user to specific roles you will use this

           var user = new ApplicationUser
            {
                UserName = "tresorunikin",
                Email = "[email protected]",
                EmailConfirmed =true
            };

            var userResult = await UserManager.CreateAsync(user, "[email protected]");
            if(userResult.Succeeded){
            string[] roles =new string[]{"admin","seller","other"};
           var roleResult = await UserManager.AddToRolesAsync(user.Id, roles);
            if(roleResult.Succeeded){
                //Here, user has been added to roles
             }
           }

All these are done for you by Pranav Rastogi, one of the Identity team at Microsoft.

Note that with these samples you target a new (beta) version of System.Web.Mvc that is newer than System.Web.Mvc 5.0.0.0 If I remember well the beta version is System.Web.MVC 5.0.1.2 or something like that

To Learn More about Identity click here

UPDATES The Version in the samples is: System.Web.Mvc 5.2.1.0

like image 175
4 revs Avatar answered Oct 15 '22 23:10

4 revs