Search code examples
asp.net-coreasp.net-identity

Assign role to user


I have a problem with assign role to user. I'm using .net Core 2.1

I changed the registration method. During registration, I assign the role of "Admin" to the user being created.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {

                var db = new ApplicationDbContext(_optionsBuilder.Options);
                var email = db.Users.Where(s => s.Email == Input.Email);
                if (email.Count() != 0)
                {
                    ViewData["duplicateEmail"] = "Email is already taken";
                    return Page();
                }

                var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                    //#############

                    if(!await _roleManager.RoleExistsAsync("Admin"))
                    {
                       await _userManager.AddToRoleAsync(user, "Admin");
                    }

                    //################
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

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

I added only code between hashtags.

After starting the application, when i click registration, i see

Issue

I tried to add

services.AddIdentity<IdentityUser,IdentityRole>()
        .AddDefaultUI()
        .AddEntityFrameworkStores<ApplicationDbContext>();

to startup

but it does not work.

How i'm doinw wrong?


Solution

  • You need to inject RoleManager<IdentityRole> in RegisterModel like:

     public class RegisterModel : PageModel
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;
        private readonly ILogger<RegisterModel> _logger;
        private readonly IEmailSender _emailSender;
    
        public RegisterModel(
             RoleManager<IdentityRole> roleManager,
            UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            ILogger<RegisterModel> logger,
            IEmailSender emailSender)
        {
            _roleManager = roleManager;
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
        }
    

    Then try to add AddRoleManager to your configureServices like:

    services.AddIdentity<IdentityUser, IdentityRole>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultUI()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();