Introduction
Creating Roles for the application
We have two types of users in the application I created in the previous article. We will create two types of users to login through the registration form created in the previous article. The users will be admin and customer users. As we worked on the create function to create a new user, now we will work on different kinds of roles that we can assign to each user trying to create an account in this particular application.
Let’s add two roles in our database. In order to add roles, we can create a static class. To create a class, right-click on the project, click on Add and then select folder. This will add a new folder named utility.
Now right click on the utility folder. Click on add, then select class option to add a static class named sd.
This class will contain all the constants:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace SparkAutomation.Utility
- {
- public class SD
- {
- public const string AdminEndUser = "Admin";
- public const string CustomerEndUser = "Customer";
-
- }
- }
Next, we add constants to different types of roles for the website. The two constants are AdminEndUser and CustomerEndUser.
Now in our application, if we want to login as admin we can reference to AdminEndUser and if we want to login as a customer we can reference to CustomerEndUser inside a static class.
Now inside the registration form, when a new user is added we can make them admin for a default scenario.
We can create a new user inside the post handler. Inside the post hander, we have to create an application user and we have to assign all of the properties as well such as username, email, name, address, city, postal code, and phone number.
- var user = new ApplicationUser
- {
- UserName = Input.Email,
- Email = Input.Email,
- Name = Input.Name,
- Address = Input.Address,
- City = Input.City,
- PostalCode = Input.PostalCode,
- PhoneNumber = Input.PhoneNumber
- };
Now once a user is created, we can create roles as well. In order to add roles, we have to get role manager using dependency injection. While saving changes inside database for any newly created use of database object as well.
- private readonly RoleManager<IdentityRole> _roleManager;
- private readonly ApplicationDbContext _db;
We have to add them inside RegisterModel constructor as follows.
- public RegisterModel(
- UserManager<IdentityUser> userManager,
- SignInManager<IdentityUser> signInManager,
- ILogger<RegisterModel> logger,
- IEmailSender emailSender,
- RoleManager<IdentityRole> roleManager,
- ApplicationDbContext db)
- {
- _userManager = userManager;
- _signInManager = signInManager;
- _logger = logger;
- _emailSender = emailSender;
- _db = db;
- _roleManager = roleManager;
- }
Here, we are adding two read only properties inside dependency injection, which are roleManager and ApplicationDbContext.
Inside the post handler, when the user is created we are checking if the roles exist in the database or not. If the user does not exist, we can create it for both admin and customer using the below line of code.
- if (result.Succeeded)
- {
- if (!await _roleManager.RoleExistsAsync(SD.AdminEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.AdminEndUser));
- }
-
- if (!await _roleManager.RoleExistsAsync(SD.CustomerEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEndUser));
- }
When these lines gets executed, they will create new roles inside database. Once a role is create we can assign it to the user using below line of code.
- await _userManager.AddToRoleAsync(user,SD.AdminEndUser);
We have to add the IdentityRole to the pipeline inside the startup.cs file so that the application will run properly.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options =>
- options.UseSqlServer(
- Configuration.GetConnectionString("DefaultConnection")));
-
- services.AddIdentity<IdentityUser,IdentityRole>()
- .AddDefaultTokenProviders()
- .AddDefaultUI()
- .AddEntityFrameworkStores<ApplicationDbContext>();
- services.AddRazorPages().AddRazorRuntimeCompilation();
- }
Now IdentityRole will be added and configured inside the application.
Register.cshml.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- using System.Text.Encodings.Web;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Identity.UI.Services;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using Microsoft.AspNetCore.WebUtilities;
- using Microsoft.Extensions.Logging;
- using SparkAutomation.Data;
- using SparkAutomation.Models;
- using SparkAutomation.Utility;
-
- namespace SparkAutomation.Areas.Identity.Pages.Account
- {
- [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;
- private readonly ApplicationDbContext _db;
-
- public RegisterModel(
- UserManager<IdentityUser> userManager,
- SignInManager<IdentityUser> signInManager,
- ILogger<RegisterModel> logger,
- IEmailSender emailSender,
- RoleManager<IdentityRole> roleManager,
- ApplicationDbContext db)
- {
- _userManager = userManager;
- _signInManager = signInManager;
- _logger = logger;
- _emailSender = emailSender;
- _db = db;
- _roleManager = roleManager;
- }
-
- [BindProperty]
- public InputModel Input { get; set; }
-
- public string ReturnUrl { get; set; }
-
- public IList<AuthenticationScheme> ExternalLogins { get; set; }
-
- public class InputModel
- {
- [Required]
- [EmailAddress]
- [Display(Name = "Email")]
- public string Email { get; set; }
-
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string Password { get; set; }
-
- [DataType(DataType.Password)]
- [Display(Name = "Confirm password")]
- [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
- public string ConfirmPassword { get; set; }
-
- [Required]
- public string Name { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string PostalCode { get; set; }
-
- [Required]
- public string PhoneNumber { get; set; }
- }
-
- public async Task OnGetAsync(string returnUrl = null)
- {
- ReturnUrl = returnUrl;
- ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
- }
-
- public async Task<IActionResult> OnPostAsync(string returnUrl = null)
- {
- returnUrl = returnUrl ?? Url.Content("~/");
- ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
- if (ModelState.IsValid)
- {
- var user = new ApplicationUser
- {
- UserName = Input.Email,
- Email = Input.Email,
- Name = Input.Name,
- Address = Input.Address,
- City = Input.City,
- PostalCode = Input.PostalCode,
- PhoneNumber = Input.PhoneNumber
- };
- var result = await _userManager.CreateAsync(user, Input.Password);
- if (result.Succeeded)
- {
- if (!await _roleManager.RoleExistsAsync(SD.AdminEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.AdminEndUser));
- }
-
- if (!await _roleManager.RoleExistsAsync(SD.CustomerEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEndUser));
- }
- await _userManager.AddToRoleAsync(user,SD.AdminEndUser);
- _logger.LogInformation("User created a new account with password.");
-
- var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
- code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
- var callbackUrl = Url.Page(
- "/Account/ConfirmEmail",
- pageHandler: null,
- values: new { area = "Identity", 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 (_userManager.Options.SignIn.RequireConfirmedAccount)
- {
- return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
- }
- else
- {
- await _signInManager.SignInAsync(user, isPersistent: false);
- return LocalRedirect(returnUrl);
- }
- }
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError(string.Empty, error.Description);
- }
- }
-
-
- return Page();
- }
- }
- }
After running the application on the browser, we can create a new user and that user will be assigned a role.
Inside the database, we can see the AspNetUsers table has been populated with columns such as username, email, name, city, address, and postal code.
The table AspNetRoles also contains two rows. One for admin and another one for the customer. Here, two roles have been added, admin and customer.
Summary
In this article, we implemented a registration functionality for admin and user. We created two roles so when a new user is created, these roles are assigned to them accordingly. We made changes inside the register razor page to include identity roles for the newly created user.