Assign user to role during Registration

Ronald Rex 1,666 Reputation points
2021-11-11T04:06:30.917+00:00

Hi Friends !!! I was wondering when a user Registers to my website can I assign them to a default role with the minimal privileges until I choose to add them to another role? Just wondering does the Startup.cs have some sort of Configuration that handles this. I have seen tutorials where they allow the user when they register to select a role. This does not make sense to me to allow a user to assign themselves to the Admin role. Again, I would like to put them in a default role. I am using Identity Core for my datastore. thank You !!!

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2021-11-11T09:21:49.197+00:00

    Hi @Ronald Rex

    I was wondering when a user Registers to my website can I assign them to a default role with the minimal privileges until I choose to add them to another role? Just wondering does the Startup.cs have some sort of Configuration that handles this.

    As far as I know, there doesn't have this method to set the default role in the Startup.cs configuration.

    To set the default role when register the user (using the Asp.net core Identity), I suggest you could refer to the following steps:

    1. Add Role services to Identity Append AddRoles to add Role services:
      public void ConfigureServices(IServiceCollection services)  
      {  
          services.AddDbContext<ApplicationDbContext>(options =>  
              options.UseSqlServer(  
                  Configuration.GetConnectionString("DefaultConnection")));  
          services.AddDefaultIdentity<IdentityUser>()  
              .AddRoles<IdentityRole>()  
              .AddEntityFrameworkStores<ApplicationDbContext>();  
      
          services.AddControllersWithViews();  
          services.AddRazorPages();  
      }  
      
    2. Custom the Identity Register page: From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
      From the left pane of the Add New Scaffolded Item dialog, select Identity > Add.
      In the Add Identity dialog, select the options you want, then click the Add button. Here we need to use the Register page: 148468-image.png Then, we can find the Register.cshtml page from the Areas/Identity/Pages/Account folder.
      Open the Register.cshtml.cs page, and inject the RoleManager, it could use to create/find/delete roles.
      [AllowAnonymous]  
      public class RegisterModel : PageModel  
      {  
          private readonly SignInManager<IdentityUser> _signInManager;  
          private readonly UserManager<IdentityUser> _userManager;  
          private readonly ILogger<RegisterModel> _logger;  
          private readonly IEmailSender _emailSender;  
          private readonly RoleManager<IdentityRole> _roleManager;  
          public RegisterModel(  
              UserManager<IdentityUser> userManager,  
              SignInManager<IdentityUser> signInManager,  
              ILogger<RegisterModel> logger,  
              RoleManager<IdentityRole> roleManager,  
              IEmailSender emailSender)  
          {  
              _userManager = userManager;  
              _signInManager = signInManager;  
              _logger = logger;  
              _roleManager = roleManager;  
              _emailSender = emailSender;  
          }  
      
      Then, in the OnPostAsync method, after user created success, we could use RoleManager to find the default role, and then, use UserManager to add user to Role. Code like this:
      public async Task<IActionResult> OnPostAsync(string returnUrl = null)  
      {  
          returnUrl ??= Url.Content("~/");  
          ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
          if (ModelState.IsValid)  
          {  
              var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };  
              var result = await _userManager.CreateAsync(user, Input.Password);  
              if (result.Succeeded)  
              {  
                  var defaultrole = _roleManager.FindByNameAsync("Default").Result;  
      
                  if (defaultrole != null)  
                  {  
                    IdentityResult roleresult = await  _userManager.AddToRoleAsync(user, defaultrole.Name);  
                  }  
      
      Finally, if we register a new user, the result as below: 148469-image.png

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    4 people found this answer helpful.

0 additional answers

Sort by: Most helpful