

Part-1 |Blazor WebAssembly[.NET 7] JWT Authentication Series | User Registration
source link: https://www.learmoreseekmore.com/2023/03/part1-blazorwebassembly-dotnet7-jwt-authentication-series-user-registratio.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The main objectives of this article are:
- In The API Project, We Will Create A User Registration Endpoint.
- In Blazor WebAssembly Application We Will Create A User Registration Form.
User Table SQL Script:
CREATE TABLE [dbo].[User]( [Id] INT IDENTITY(1000,1) NOT NULL, [FirstName] VARCHAR(300) NULL, [LastName] VARCHAR(300) NULL, [Email] VARCHAR(300) NULL, [Password] VARCHAR(500) NULL CONSTRAINT PK_User PRIMARY KEY (Id) )
Create A .NET7 Blazor WebAssembly Application:
Setup MudBlazor:
@using MudBlazor
Add the below CSS into the closing head tag in 'wwwroot/index.html'.
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" /> <link href="_content/MudBlazor/MudBlazor.min.css" rel="stylesheet" />
Remove the below CSS reference in the 'wwwroot/index.html'.
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
In the 'Program.cs' file register the MudBlazor service.
using MudBlazor.Services; builder.Services.AddMudServices();
In 'MainLayout.razor' file add the below MudBlazor components
- @inherits LayoutComponentBase
- <MudThemeProvider />
- <MudDialogProvider />
- <MudSnackbarProvider />
- <MudLayout>
- <MudAppBar Color="Color.Primary" Fixed="false">
- JWT Auth Demo
- </MudAppBar>
- <MudMainContent>
- @Body
- </MudMainContent>
- </MudLayout>
Install FluentValidation Library:
Add the FluentValidation library namespace in '_Import.razor'
@using FluentValidation
Create 'RegistrationVm' For Form Model:
- namespace JWT.Auth.BlazorUI.ViewModels.Account
- public class RegistrationVM
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Email { get; set; }
- public string Password { get; set; }
- public string ConfirmPassword { get; set; }
Create A Validation Model 'RegistrationValidationVm':
- using FluentValidation;
- namespace JWT.Auth.BlazorUI.ViewModels.Account
- public class RegistrationValidationVm:AbstractValidator<RegistrationVM>
- public RegistrationValidationVm()
- RuleFor(_ => _.FirstName).NotEmpty();
- RuleFor(_ => _.LastName).NotEmpty();
- RuleFor(_ => _.Email).EmailAddress().NotEmpty();
- RuleFor(_ => _.Password).NotEmpty().WithMessage("Your password cannot be empty")
- .MinimumLength(6).WithMessage("Your password length must be at least 6.")
- .MaximumLength(16).WithMessage("Your password length must not exceed 16.")
- .Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.")
- .Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.")
- .Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.")
- .Matches(@"[\@\!\?\*\.]+").WithMessage("Your password must contain at least one (@!? *.).");
- RuleFor(_ => _.ConfirmPassword).Equal(_ => _.Password).WithMessage("ConfirmPassword must equal Password");
- public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
- var result = await ValidateAsync(ValidationContext<RegistrationVM>.CreateWithOptions((RegistrationVM)model, x => x.IncludeProperties(propertyName)));
- if (result.IsValid)
- return Array.Empty<string>();
- return result.Errors.Select(e => e.ErrorMessage);
- (Line: 4) Inherits 'FluentValidation.AbstractValidatory<TEntity>' where TEntity is our form model(RegistrationVm)
- (Line: 10) Configured email validation.
- (Line: 11-17) Configured password validation rules.
- (Line: 19) Configured the 'ConfirmPassword' must match with the 'Password' value.
- (21-27) The 'ValidateValue' arrow function collects the error messages. This will be used by our MudBlazor form.
Add the namespace into the '_Import.razor'.
@using JWT.Auth.BlazorUI.ViewModels.Account
Create 'Registration.razor' Component:
- @page "/registration"
- <div class="ma-6 d-flex justify-center">
- <MudChip Color="Color.Primary">
- <h3>Registration Form</h3>
- </MudChip>
- </div>
- <div class="ma-6 d-flex justify-center">
- <MudCard Width="500px">
- <MudForm Model="registrationModel" @ref="form" Validation="registrationValidator.ValidateValue">
- <MudCardContent>
- <MudTextField @bind-Value="registrationModel.FirstName"
- For="@(() => registrationModel.FirstName)"
- Immediate="true"
- Label="First Name" />
- <MudTextField @bind-Value="registrationModel.LastName"
- For="@(() => registrationModel.LastName)"
- Immediate="true"
- Label="Last Name" InputType="InputType.Email" />
- <MudTextField @bind-Value="registrationModel.Email"
- For="@(() => registrationModel.Email)"
- Immediate="true"
- Label="Email" />
- <MudTextField @bind-Value="registrationModel.Password"
- For="@(() => registrationModel.Password)"
- Immediate="true"
- Label="Password" InputType="InputType.Password" />
- <MudTextField @bind-Value="registrationModel.ConfirmPassword"
- For="@(() => registrationModel.ConfirmPassword)"
- Immediate="true"
- Label="Confirm Password" InputType="InputType.Password" />
- <MudCardActions>
- <MudButton Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" OnClick="RegisterAsync">Register</MudButton>
- </MudCardActions>
- </MudCardContent>
- </MudForm>
- </MudCard>
- </div>
- (Line: 10) The 'Model' attribute registered with 'registrationModel' variable of type 'RegistrationVm'. The '@ref' directive gives control over the 'MudForm' and it was mapped with 'form' variable of type 'MudForm'. The 'Validation' attribute is registered with 'RegistrationValidationVm.ValidateValue' arrow function.
- (Line: 33) Here submit button is registered with the 'RegisterAsync' method.
Pages/Account/Registration.razor:(c# Part)
- @code {
- RegistrationVM registrationModel = new RegistrationVM();
- RegistrationValidationVm registrationValidator = new RegistrationValidationVm();
- MudForm form;
- private async Task RegisterAsync()
- await form.Validate();
- if (form.IsValid)
- // invoke register API call.
Add the registration page link on the nav bar menu.
- @inherits LayoutComponentBase
- <MudThemeProvider />
- <MudDialogProvider />
- <MudSnackbarProvider />
- <MudLayout>
- <MudAppBar Color="Color.Primary" Fixed="false">
- <MudLink Underline="Underline.None" Color="Color.Inherit" Href="/">JWT Auth Demo</MudLink>
- <MudSpacer />
- <MudLink Underline="Underline.None" Color="Color.Inherit" Href="/registration">Registration</MudLink>
- </MudAppBar>
- <MudMainContent>
- @Body
- </MudMainContent>
- </MudLayout>
Create .NET 7 API Project:
Install Entity FrameworkCore NuGet Package:
SQL Connection String:
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyWorldDB;Integrated Security=True;Connect Timeout=30
- Data Source - SQL server name.
- Initial Catalog - Database name.
- Integrated Security - windows authentication.
- Connect Time - connection time period.
"ConnectionStrings": { "MyWorldDbConnection": "" }
Configure Database Context In API Project:
- namespace JWT.Auth.API.Data.Entities
- public class User
- public int Id { get; set; }
- public string? FirstName { get; set; }
- public string? LastName { get; set; }
- public string? Email { get; set; }
- public string? Password { get; set; }
To manage or control all the table classes in c# we have to create the DatabaseContext class. So let's create our context class like 'MyWorldDbContext.cs' in the 'Data' folder.
- using JWT.Auth.API.Data.Entities;
- using Microsoft.EntityFrameworkCore;
- namespace JWT.Auth.API.Data
- public class MyWorldDbContext:DbContext
- public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options):base(options)
- public DbSet<User> User { get; set; }
- (Line: 6) The 'Microsoft.EntityFramwork.DbContext' needs to be inherited by our 'MyWorldDbContext' to act as a database context class.
- (Line: 8) The 'Microsoft.EntityFramworkCore.DbContextOptions' is an instance of options that we are going to register in 'Program.cs' like 'ConnectionString', 'DatabaseProvider', etc.
- (Line: 12) All our table classes, must be registered inside of our database context class with 'DbSet<T>' so that the entity framework can communicate with the table of the database.
Register database context in 'Program.cs'.
builder.Services.AddDbContext<MyWorldDbContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("MyWorldDbConnection")); });
Implement User Registration Endpoint:
- namespace JWT.Auth.API.Dtos
- public class UserRegistrationDto
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Email { get; set; }
- public string Password { get; set; }
- public string ConfirmPassword { get; set; }
Let's create a new service interface like 'IUserService.cs' in the 'Services' folder(new folder).
- using JWT.Auth.API.Dtos;
- namespace JWT.Auth.API.Services
- public interface IUserService
- Task<(bool IsUserRegistered, string Message)> RegisterNewUser(UserRegistrationDto userRegistration);
Let's create a new service class like 'UserService' in the 'Services' folder and implement the 'RegisterNewUser' method.
- using JWT.Auth.API.Data;
- using JWT.Auth.API.Data.Entities;
- using JWT.Auth.API.Dtos;
- using System.Security.Cryptography;
- namespace JWT.Auth.API.Services
- public class UserService : IUserService
- private readonly MyWorldDbContext _dbContext;
- public UserService(MyWorldDbContext dbContext)
- _dbContext = dbContext;
- private User FromUserRegistrationModelToUser(UserRegistrationDto userRegistration)
- return new User
- Email = userRegistration.Email,
- FirstName = userRegistration.FirstName,
- Password = userRegistration.Password,
- LastName = userRegistration.LastName,
- private string HashedPassword(string plainPassword)
- byte[] salt = new byte[16];
- using (var randomGenerator = RandomNumberGenerator.Create())
- randomGenerator.GetBytes(salt);
- var rfcPassowrd = new Rfc2898DeriveBytes(plainPassword, salt, 1000, HashAlgorithmName.SHA1);
- byte[] rfcPasswordHash = rfcPassowrd.GetBytes(20);
- byte[] passwordHash = new byte[36];
- Array.Copy(salt, 0, passwordHash, 0, 16);
- Array.Copy(rfcPasswordHash, 0, passwordHash, 16, 20);
- return Convert.ToBase64String(passwordHash);
- public async Task<(bool IsUserRegistered, string Message)> RegisterNewUser(UserRegistrationDto userRegistration)
- var isUserExist = _dbContext.User.Any(_ => _.Email.ToLower() == userRegistration.Email.ToLower());
- if (isUserExist)
- return (false, "Email Already Registered");
- var newUser = FromUserRegistrationModelToUser(userRegistration);
- newUser.Password = HashedPassword(newUser.Password);
- _dbContext.User.Add(newUser);
- await _dbContext.SaveChangesAsync();
- return (true, "Success");
- (Line: 16-25) The 'FromUserRegistrationModelToUser' method to map our payload to the 'User' entity.
- (Line: 27-42) The 'HashedPassword' method generates an encrypted password.
- (Line: 27) Here we will pass our plain password as an input parameter.
- (Line: 29-33) To hash any password, we should have a salt key. Here we are going to define 16-byte array of salt. Using the 'System.Security.Cryptography.RandomNumberGenerator' we generate the 16-byte salt key.
- (Lines: 34&35) Here initialized the 'System.Security.Cryptography.Rfc2898DeriveBytes' instance. Here first parameter will be the 'our password'(plain password), the second parameter will be the '16-byte salt key', the third parameter is 'number of iterations to do hashing', and the fourth parameter is the hashing algorithm. Finally takes 20 bytes of hashed password.
- (Line: 37-39) Here we defined the final size of our password to 36-byte. The first 16 bytes are the 'salt' key and the next 20 bytes are the 'hashed password'.
- (Line: 44-60) The 'RegisterNewUser' method contains logic to register the user.
- (Line: 46-51) Checks whether the user is already registered or not.
- (Line: 53-58) Inserting the user into the table.
Let's register our 'IUserService' & 'UserService' in 'Program.cs'
builder.Services.AddScoped<IUserService, UserService>();
Let's create the user registration post endpoint.
- using JWT.Auth.API.Dtos;
- using JWT.Auth.API.Services;
- using Microsoft.AspNetCore.Mvc;
- namespace JWT.Auth.API.Controllers
- [Route("api/[controller]")]
- [ApiController]
- public class UserController : ControllerBase
- private readonly IUserService _userService;
- public UserController(IUserService userService)
- _userService = userService;
- [HttpPost("register")]
- public async Task<IActionResult> RegisterUser(UserRegistrationDto userRegistration)
- var result = await _userService.RegisterNewUser(userRegistration);
- if (result.IsUserRegistered)
- return Ok(result.Message);
- ModelState.AddModelError("Email", result.Message);
- return BadRequest(ModelState);
- Here if the user registered already then we will return the bad request as a response.
Blazor WebAssembly App Invoke User Registration Endpoint:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7045/") });
Now invoke the user registration endpoint in the 'Registration.razor' component.
- @page "/registration"
- @using System.Text.Json;
- @using System.Text;
- @inject HttpClient _httpClient
- @inject NavigationManager _navigationManager
- <div class="ma-6 d-flex justify-center">
- <MudChip Color="Color.Primary">
- <h3>Registration Form</h3>
- </MudChip>
- </div>
- <div class="ma-6 d-flex justify-center">
- <MudCard Width="500px">
- <MudForm Model="registrationModel" @ref="form" Validation="registrationValidator.ValidateValue">
- <MudCardContent>
- @if (!string.IsNullOrEmpty(APIErrorMessage))
- <MudChip Class="d-flex justify-center" Color="Color.Error">
- <h3>@APIErrorMessage</h3>
- </MudChip>
- <MudTextField @bind-Value="registrationModel.FirstName"
- For="@(() => registrationModel.FirstName)"
- Immediate="true"
- Label="First Name" />
- <MudTextField @bind-Value="registrationModel.LastName"
- For="@(() => registrationModel.LastName)"
- Immediate="true"
- Label="Last Name" InputType="InputType.Email" />
- <MudTextField @bind-Value="registrationModel.Email"
- For="@(() => registrationModel.Email)"
- Immediate="true"
- Label="Email" />
- <MudTextField @bind-Value="registrationModel.Password"
- For="@(() => registrationModel.Password)"
- Immediate="true"
- Label="Password" InputType="InputType.Password" />
- <MudTextField @bind-Value="registrationModel.ConfirmPassword"
- For="@(() => registrationModel.ConfirmPassword)"
- Immediate="true"
- Label="Confirm Password" InputType="InputType.Password" />
- <MudCardActions>
- <MudButton Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" OnClick="RegisterAsync">Register</MudButton>
- </MudCardActions>
- </MudCardContent>
- </MudForm>
- </MudCard>
- </div>
- (Line: 4) Injected the HTPP Client instance
- (Line: 5) Injected the NavigationManager instance.
- (Line: 17-22) Here we will render the API error messages.
BlazorWasm_Project/Pages/Accounts/Registration.razor:(C# Part)
- @code {
- RegistrationVM registrationModel = new RegistrationVM();
- RegistrationValidationVm registrationValidator = new RegistrationValidationVm();
- MudForm form;
- string APIErrorMessage = string.Empty;
- private async Task RegisterAsync()
- await form.Validate();
- if (form.IsValid)
- // invoke register API call.
- var jsonPayload = JsonSerializer.Serialize(registrationModel);
- var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
- var response = await _httpClient.PostAsync("/api/user/register", requestContent);
- if(response.StatusCode == System.Net.HttpStatusCode.BadRequest)
- var errors = await response.Content
- .ReadFromJsonAsync<Dictionary<string, List<string>>>();
- if(errors.Count > 0)
- foreach (var item in errors)
- foreach (var errorMessage in item.Value)
- APIErrorMessage = $"{errorMessage} | ";
- else if(response.StatusCode == System.Net.HttpStatusCode.OK)
- _navigationManager.NavigateTo("/registration-confirmation");
- APIErrorMessage = "Failed To Register User Please Try After SomeTime";
- (Line: 11-46) Here invoking the user registration post API call. If the API returns Bad Request or any other error response then we will assign an error value to 'APIErrorMessage' variable. If the API returns success then we will navigate to the 'RegistrationConfirmation' component.
Now let's create the new component like 'RegistrationConfirmation.razor'
- @page "/registration-confirmation"
- <div class="ma-6 d-flex justify-center">
- <MudChip Color="Color.Primary">
- <h3>Registration Successfull. Please Login!</h3>
- </MudChip>
- </div>
- @code {
(Step 1)
Implement Unique Email Validation In Blazor WebAssembly:
- bool CheckUserUniqueEmail(string email);
Now implement the 'CheckUserUniqueEmail' method in 'UserService.cs'.
- public bool CheckUserUniqueEmail(string email)
- var userAlreadyExist = _dbContext.User.Any(_ => _.Email.ToLower() == email.ToLower());
- return !userAlreadyExist;
- Here we checking the email is unique or not.
Now add the Unique email verification endpoint in our 'UserController'.
- [HttpGet("unique-user-email")]
- public IActionResult CheckUserUniqueEmail(string email)
- var result = _userService.CheckUserUniqueEmail(email);
- return Ok(result);
Now add the HTTP call in 'RegistrationValidationVm' in Blazor Application.
- using FluentValidation;
- using System.Text.Json;
- using System.Text.RegularExpressions;
- using System.Threading;
- namespace JWT.Auth.BlazorUI.ViewModels.Account
- public class RegistrationValidationVm:AbstractValidator<RegistrationVM>
- private readonly HttpClient _httpClient;
- public RegistrationValidationVm(HttpClient httpClient)
- _httpClient = httpClient;
- RuleFor(_ => _.FirstName).NotEmpty();
- RuleFor(_ => _.LastName).NotEmpty();
- RuleFor(_ => _.Email).NotEmpty()
- .EmailAddress()
- .MustAsync(async(value , cancellationToken) => await UniqueEmail(value))
- .When(_ => !string.IsNullOrEmpty(_.Email) && Regex.IsMatch(_.Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase), ApplyConditionTo.CurrentValidator)
- .WithMessage("email should be unique");
- RuleFor(_ => _.Password).NotEmpty().WithMessage("Your password cannot be empty").MinimumLength(6).WithMessage("Your password length must be at least 6.").WithMessage("email should be unique")
- .MaximumLength(16).WithMessage("Your password length must not exceed 16.")
- .Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.")
- .Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.")
- .Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.")
- .Matches(@"[\@\!\?\*\.]+").WithMessage("Your password must contain at least one (@!? *.).");
- RuleFor(_ => _.ConfirmPassword).Equal(_ => _.Password).WithMessage("ConfirmPassword must equal Password");
- public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
- var result = await ValidateAsync(ValidationContext<RegistrationVM>.CreateWithOptions((RegistrationVM)model, x => x.IncludeProperties(propertyName)));
- if (result.IsValid)
- return Array.Empty<string>();
- return result.Errors.Select(e => e.ErrorMessage);
- private async Task<bool> UniqueEmail(string email)
- if (string.IsNullOrEmpty(email))
- return true;
- string url = $"/api/user/unique-user-email?email={email}";
- var response = await _httpClient.GetAsync(url);
- response.EnsureSuccessStatusCode();
- var content = await response.Content.ReadAsStringAsync();
- return JsonSerializer.Deserialize<bool>(content);
- catch (Exception e)
- return false;
- (Line: 39-58) Here 'UniqueEmail' method returns a boolean value, if it returns 'false' then a validation error raises. Here we invoke the 'unique-user-email' API endpoint.
- (Line: 16-20) Here registered 'MustAsync' which internally invokes our 'UniqueEmail' method. But to avoid execution of the 'MustAsync' method on every user keystroke for the email field we used the 'When' method so that 'MustAsync' only executes when a user enters the proper email.
In 'Registration.razor' component we have to pass the 'HTTP' client instance to the 'RegistrationValidationVm' object.
- @code {
- RegistrationVM registrationModel = new RegistrationVM();
- RegistrationValidationVm registrationValidator;
- MudForm form;
- string APIErrorMessage = string.Empty;
- protected override Task OnInitializedAsync()
- registrationValidator = new RegistrationValidationVm(_httpClient);
- return base.OnInitializedAsync();
- private async Task RegisterAsync()
- await form.Validate();
- if (form.IsValid)
- // invoke register API call.
- var jsonPayload = JsonSerializer.Serialize(registrationModel);
- var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
- var response = await _httpClient.PostAsync("/api/user/register", requestContent);
- if(response.StatusCode == System.Net.HttpStatusCode.BadRequest)
- var errors = await response.Content
- .ReadFromJsonAsync<Dictionary<string, List<string>>>();
- if(errors.Count > 0)
- foreach (var item in errors)
- foreach (var errorMessage in item.Value)
- APIErrorMessage = $"{errorMessage} | ";
- else if(response.StatusCode == System.Net.HttpStatusCode.OK)
- _navigationManager.NavigateTo("/registration-confirmation");
- APIErrorMessage = "Failed To Register User Please Try After SomeTime";
- (Line: 12) Passing the HttpClient instance to the 'RegistrationValidationVm'.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Follow Me:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK