2

Part-1 |Blazor WebAssembly[.NET 7] JWT Authentication Series | User Registration

 1 year ago
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.
ReactJS(v18)%20Form%20Validation%20%20React%20Hook%20Form(v7)%20%20React%20Bootstrap%20UI%20Form%20Components%20(1).png

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:

Run the below script to create the 'User' table.
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:

Let's create a Blazor WebAssembly application using Visual Studio 2022.
(Step 1)
1.PNG
(Step 2)
2.PNG
(Step 3)
3.PNG

Setup MudBlazor:

Install the MudBlazor library.
4.PNG
Add the MudBlazor namespace in '_Import.razor'.
@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'.

4-2.PNG
Add script tag just above the closing body tag in 'wwwroot/index.html'
<script src="_content/MudBlazor/MudBlazor.min.js"></script>

In the 'Program.cs' file register the MudBlazor service.

Program.cs:
using MudBlazor.Services;

builder.Services.AddMudServices();

In 'MainLayout.razor' file add the below MudBlazor components

Shared/MainLayout.razor:


  1. @inherits LayoutComponentBase
  2. <MudThemeProvider />
  3. <MudDialogProvider />
  4. <MudSnackbarProvider />
  5. <MudLayout>
  6. <MudAppBar Color="Color.Primary" Fixed="false">
  7. JWT Auth Demo
  8. </MudAppBar>
  9. <MudMainContent>
  10. @Body
  11. </MudMainContent>
  12. </MudLayout>
4-3.PNG

Install FluentValidation Library:

We are going to use the FluentVlaidation library for the MudBlazor form to apply validation rules.
So install the FluentValidation library.
5.PNG

Add the FluentValidation library namespace in '_Import.razor'

_Import.razor:
@using FluentValidation

Create 'RegistrationVm' For Form Model:

Let's create a form model like 'RegistrationVm' in the 'ViewModels/Account' folder(new folders).
ViewModels/Account/RegistrationVm.cs:


  1. namespace JWT.Auth.BlazorUI.ViewModels.Account
  2. public class RegistrationVM
  3. public string FirstName { get; set; }
  4. public string LastName { get; set; }
  5. public string Email { get; set; }
  6. public string Password { get; set; }
  7. public string ConfirmPassword { get; set; }

Create A Validation Model 'RegistrationValidationVm':

Now to add FluentValidation rules on 'RegistrationVm' let's create a model like 'RegistrationValidationVm' in the 'ViewModels/Account' folder.
ViewModels/Account/RegistrationValidationVm.cs:


  1. using FluentValidation;
  2. namespace JWT.Auth.BlazorUI.ViewModels.Account
  3. public class RegistrationValidationVm:AbstractValidator<RegistrationVM>
  4. public RegistrationValidationVm()
  5. RuleFor(_ => _.FirstName).NotEmpty();
  6. RuleFor(_ => _.LastName).NotEmpty();
  7. RuleFor(_ => _.Email).EmailAddress().NotEmpty();
  8. RuleFor(_ => _.Password).NotEmpty().WithMessage("Your password cannot be empty")
  9. .MinimumLength(6).WithMessage("Your password length must be at least 6.")
  10. .MaximumLength(16).WithMessage("Your password length must not exceed 16.")
  11. .Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.")
  12. .Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.")
  13. .Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.")
  14. .Matches(@"[\@\!\?\*\.]+").WithMessage("Your password must contain at least one (@!? *.).");
  15. RuleFor(_ => _.ConfirmPassword).Equal(_ => _.Password).WithMessage("ConfirmPassword must equal Password");
  16. public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
  17. var result = await ValidateAsync(ValidationContext<RegistrationVM>.CreateWithOptions((RegistrationVM)model, x => x.IncludeProperties(propertyName)));
  18. if (result.IsValid)
  19. return Array.Empty<string>();
  20. 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'.

_Import.razor:
@using JWT.Auth.BlazorUI.ViewModels.Account

Create 'Registration.razor' Component:

Let's create page-level component like 'Registration.razor' in the 'Pages/Account' folder.
Pages/Account/Registration.razor:(HTML Part)


  1. @page "/registration"
  2. <div class="ma-6 d-flex justify-center">
  3. <MudChip Color="Color.Primary">
  4. <h3>Registration Form</h3>
  5. </MudChip>
  6. </div>
  7. <div class="ma-6 d-flex justify-center">
  8. <MudCard Width="500px">
  9. <MudForm Model="registrationModel" @ref="form" Validation="registrationValidator.ValidateValue">
  10. <MudCardContent>
  11. <MudTextField @bind-Value="registrationModel.FirstName"
  12. For="@(() => registrationModel.FirstName)"
  13. Immediate="true"
  14. Label="First Name" />
  15. <MudTextField @bind-Value="registrationModel.LastName"
  16. For="@(() => registrationModel.LastName)"
  17. Immediate="true"
  18. Label="Last Name" InputType="InputType.Email" />
  19. <MudTextField @bind-Value="registrationModel.Email"
  20. For="@(() => registrationModel.Email)"
  21. Immediate="true"
  22. Label="Email" />
  23. <MudTextField @bind-Value="registrationModel.Password"
  24. For="@(() => registrationModel.Password)"
  25. Immediate="true"
  26. Label="Password" InputType="InputType.Password" />
  27. <MudTextField @bind-Value="registrationModel.ConfirmPassword"
  28. For="@(() => registrationModel.ConfirmPassword)"
  29. Immediate="true"
  30. Label="Confirm Password" InputType="InputType.Password" />
  31. <MudCardActions>
  32. <MudButton Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" OnClick="RegisterAsync">Register</MudButton>
  33. </MudCardActions>
  34. </MudCardContent>
  35. </MudForm>
  36. </MudCard>
  37. </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)



  1. @code {
  2. RegistrationVM registrationModel = new RegistrationVM();
  3. RegistrationValidationVm registrationValidator = new RegistrationValidationVm();
  4. MudForm form;
  5. private async Task RegisterAsync()
  6. await form.Validate();
  7. if (form.IsValid)
  8. // invoke register API call.

Add the registration page link on the nav bar menu.

Shared/MainLayout.razor:


  1. @inherits LayoutComponentBase
  2. <MudThemeProvider />
  3. <MudDialogProvider />
  4. <MudSnackbarProvider />
  5. <MudLayout>
  6. <MudAppBar Color="Color.Primary" Fixed="false">
  7. <MudLink Underline="Underline.None" Color="Color.Inherit" Href="/">JWT Auth Demo</MudLink>
  8. <MudSpacer />
  9. <MudLink Underline="Underline.None" Color="Color.Inherit" Href="/registration">Registration</MudLink>
  10. </MudAppBar>
  11. <MudMainContent>
  12. @Body
  13. </MudMainContent>
  14. </MudLayout>
6.PNG

Create .NET 7 API Project:

Let's create .NET7 API project using Visual Studio 2022
(Step 1)
7.PNG
(Step 2)
8.PNG
(Step 3)
9.PNG
(Step 4)
10.PNG

Install Entity FrameworkCore NuGet Package:

Let's install the entity framework core into our API project.
11.PNG
Let's install the entity framework core SQL package into our API project.
12.PNG

SQL Connection String:

Let's prepare the SQL connection string.
Sample 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.
Add the connection string in the 'appsettings.Development.json'.
API_Project/appsettings.Development.json:
"ConnectionStrings": {
 "MyWorldDbConnection": ""
}

Configure Database Context In API Project:

Now add a new class that represents our 'User' table. So let's add a new folder like 'Data/Entities' and then add our new class like 'User.cs'
API_Project/Data/Entities/User.cs:


  1. namespace JWT.Auth.API.Data.Entities
  2. public class User
  3. public int Id { get; set; }
  4. public string? FirstName { get; set; }
  5. public string? LastName { get; set; }
  6. public string? Email { get; set; }
  7. 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.

API_Project/Data/MyWorldDbContext.cs:


  1. using JWT.Auth.API.Data.Entities;
  2. using Microsoft.EntityFrameworkCore;
  3. namespace JWT.Auth.API.Data
  4. public class MyWorldDbContext:DbContext
  5. public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options):base(options)
  6. 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'.

API_Project/Program.cs:
builder.Services.AddDbContext<MyWorldDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyWorldDbConnection"));
});

Implement User Registration Endpoint: 

Let's create a payload object like 'UserRegistrationDto' in the 'Dtos' folder(new folder).
API_Project/Dtos/UserRegistrationDto.cs:


  1. namespace JWT.Auth.API.Dtos
  2. public class UserRegistrationDto
  3. public string FirstName { get; set; }
  4. public string LastName { get; set; }
  5. public string Email { get; set; }
  6. public string Password { get; set; }
  7. public string ConfirmPassword { get; set; }

Let's create a new service interface like 'IUserService.cs' in the 'Services' folder(new folder).

API_Project/Services/IUserService.cs:


  1. using JWT.Auth.API.Dtos;
  2. namespace JWT.Auth.API.Services
  3. public interface IUserService
  4. 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.

API_Project/Services/UserService.cs:


  1. using JWT.Auth.API.Data;
  2. using JWT.Auth.API.Data.Entities;
  3. using JWT.Auth.API.Dtos;
  4. using System.Security.Cryptography;
  5. namespace JWT.Auth.API.Services
  6. public class UserService : IUserService
  7. private readonly MyWorldDbContext _dbContext;
  8. public UserService(MyWorldDbContext dbContext)
  9. _dbContext = dbContext;
  10. private User FromUserRegistrationModelToUser(UserRegistrationDto userRegistration)
  11. return new User
  12. Email = userRegistration.Email,
  13. FirstName = userRegistration.FirstName,
  14. Password = userRegistration.Password,
  15. LastName = userRegistration.LastName,
  16. private string HashedPassword(string plainPassword)
  17. byte[] salt = new byte[16];
  18. using (var randomGenerator = RandomNumberGenerator.Create())
  19. randomGenerator.GetBytes(salt);
  20. var rfcPassowrd = new Rfc2898DeriveBytes(plainPassword, salt, 1000, HashAlgorithmName.SHA1);
  21. byte[] rfcPasswordHash = rfcPassowrd.GetBytes(20);
  22. byte[] passwordHash = new byte[36];
  23. Array.Copy(salt, 0, passwordHash, 0, 16);
  24. Array.Copy(rfcPasswordHash, 0, passwordHash, 16, 20);
  25. return Convert.ToBase64String(passwordHash);
  26. public async Task<(bool IsUserRegistered, string Message)> RegisterNewUser(UserRegistrationDto userRegistration)
  27. var isUserExist = _dbContext.User.Any(_ => _.Email.ToLower() == userRegistration.Email.ToLower());
  28. if (isUserExist)
  29. return (false, "Email Already Registered");
  30. var newUser = FromUserRegistrationModelToUser(userRegistration);
  31. newUser.Password = HashedPassword(newUser.Password);
  32. _dbContext.User.Add(newUser);
  33. await _dbContext.SaveChangesAsync();
  34. 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'

API_Project/Program.cs:
builder.Services.AddScoped<IUserService, UserService>();

Let's create the user registration post endpoint.

API_Project/Controllers/UserController.cs:


  1. using JWT.Auth.API.Dtos;
  2. using JWT.Auth.API.Services;
  3. using Microsoft.AspNetCore.Mvc;
  4. namespace JWT.Auth.API.Controllers
  5. [Route("api/[controller]")]
  6. [ApiController]
  7. public class UserController : ControllerBase
  8. private readonly IUserService _userService;
  9. public UserController(IUserService userService)
  10. _userService = userService;
  11. [HttpPost("register")]
  12. public async Task<IActionResult> RegisterUser(UserRegistrationDto userRegistration)
  13. var result = await _userService.RegisterNewUser(userRegistration);
  14. if (result.IsUserRegistered)
  15. return Ok(result.Message);
  16. ModelState.AddModelError("Email", result.Message);
  17. return BadRequest(ModelState);
  • Here if the user registered already then we will return the bad request as a response.
13.PNG

Blazor WebAssembly App Invoke User Registration Endpoint:

First, enable cors in the API project to allow Blazor WebAssembly to consume API endpoints.
14.PNG
Now register the API endpoint in the Program.cs file in the Blazor WebAssembly application.
BlazorWasm_Project/Program.cs:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:7045/") });

Now invoke the user registration endpoint in the 'Registration.razor' component.

BlazorWasm_Project/Pages/Accounts/Registration.razor:(HTML Part)


  1. @page "/registration"
  2. @using System.Text.Json;
  3. @using System.Text;
  4. @inject HttpClient _httpClient
  5. @inject NavigationManager _navigationManager
  6. <div class="ma-6 d-flex justify-center">
  7. <MudChip Color="Color.Primary">
  8. <h3>Registration Form</h3>
  9. </MudChip>
  10. </div>
  11. <div class="ma-6 d-flex justify-center">
  12. <MudCard Width="500px">
  13. <MudForm Model="registrationModel" @ref="form" Validation="registrationValidator.ValidateValue">
  14. <MudCardContent>
  15. @if (!string.IsNullOrEmpty(APIErrorMessage))
  16. <MudChip Class="d-flex justify-center" Color="Color.Error">
  17. <h3>@APIErrorMessage</h3>
  18. </MudChip>
  19. <MudTextField @bind-Value="registrationModel.FirstName"
  20. For="@(() => registrationModel.FirstName)"
  21. Immediate="true"
  22. Label="First Name" />
  23. <MudTextField @bind-Value="registrationModel.LastName"
  24. For="@(() => registrationModel.LastName)"
  25. Immediate="true"
  26. Label="Last Name" InputType="InputType.Email" />
  27. <MudTextField @bind-Value="registrationModel.Email"
  28. For="@(() => registrationModel.Email)"
  29. Immediate="true"
  30. Label="Email" />
  31. <MudTextField @bind-Value="registrationModel.Password"
  32. For="@(() => registrationModel.Password)"
  33. Immediate="true"
  34. Label="Password" InputType="InputType.Password" />
  35. <MudTextField @bind-Value="registrationModel.ConfirmPassword"
  36. For="@(() => registrationModel.ConfirmPassword)"
  37. Immediate="true"
  38. Label="Confirm Password" InputType="InputType.Password" />
  39. <MudCardActions>
  40. <MudButton Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto" OnClick="RegisterAsync">Register</MudButton>
  41. </MudCardActions>
  42. </MudCardContent>
  43. </MudForm>
  44. </MudCard>
  45. </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)



  1. @code {
  2. RegistrationVM registrationModel = new RegistrationVM();
  3. RegistrationValidationVm registrationValidator = new RegistrationValidationVm();
  4. MudForm form;
  5. string APIErrorMessage = string.Empty;
  6. private async Task RegisterAsync()
  7. await form.Validate();
  8. if (form.IsValid)
  9. // invoke register API call.
  10. var jsonPayload = JsonSerializer.Serialize(registrationModel);
  11. var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
  12. var response = await _httpClient.PostAsync("/api/user/register", requestContent);
  13. if(response.StatusCode == System.Net.HttpStatusCode.BadRequest)
  14. var errors = await response.Content
  15. .ReadFromJsonAsync<Dictionary<string, List<string>>>();
  16. if(errors.Count > 0)
  17. foreach (var item in errors)
  18. foreach (var errorMessage in item.Value)
  19. APIErrorMessage = $"{errorMessage} | ";
  20. else if(response.StatusCode == System.Net.HttpStatusCode.OK)
  21. _navigationManager.NavigateTo("/registration-confirmation");
  22. 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'

BlazorWasm_Project/Pages/Accounts/RegistrationConfirmation.razor:


  1. @page "/registration-confirmation"
  2. <div class="ma-6 d-flex justify-center">
  3. <MudChip Color="Color.Primary">
  4. <h3>Registration Successfull. Please Login!</h3>
  5. </MudChip>
  6. </div>
  7. @code {

(Step 1)

15.PNG
(Step 2)
16.PNG
(Step 3)
17.PNG

Implement Unique Email Validation In Blazor WebAssembly:

Let's create an endpoint to check whether the user's email is unique or not.
Let's add the method definition 'CheckUserUniqueEmail' in 'IUserService.cs'
API_Project/Services/IUserService.cs:


  1. bool CheckUserUniqueEmail(string email);

Now implement the 'CheckUserUniqueEmail' method in 'UserService.cs'.

API_Project/Services/UserServices.cs:


  1. public bool CheckUserUniqueEmail(string email)
  2. var userAlreadyExist = _dbContext.User.Any(_ => _.Email.ToLower() == email.ToLower());
  3. return !userAlreadyExist;
  • Here we checking the email is unique or not.

Now add the Unique email verification endpoint in our 'UserController'.

API_Project/Controllers/UserController.cs:


  1. [HttpGet("unique-user-email")]
  2. public IActionResult CheckUserUniqueEmail(string email)
  3. var result = _userService.CheckUserUniqueEmail(email);
  4. return Ok(result);

Now add the HTTP call in 'RegistrationValidationVm' in Blazor Application.

BlazorWasm/ViewModels/Accounts/RegistrationValidationVm.cs:


  1. using FluentValidation;
  2. using System.Text.Json;
  3. using System.Text.RegularExpressions;
  4. using System.Threading;
  5. namespace JWT.Auth.BlazorUI.ViewModels.Account
  6. public class RegistrationValidationVm:AbstractValidator<RegistrationVM>
  7. private readonly HttpClient _httpClient;
  8. public RegistrationValidationVm(HttpClient httpClient)
  9. _httpClient = httpClient;
  10. RuleFor(_ => _.FirstName).NotEmpty();
  11. RuleFor(_ => _.LastName).NotEmpty();
  12. RuleFor(_ => _.Email).NotEmpty()
  13. .EmailAddress()
  14. .MustAsync(async(value , cancellationToken) => await UniqueEmail(value))
  15. .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)
  16. .WithMessage("email should be unique");
  17. 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")
  18. .MaximumLength(16).WithMessage("Your password length must not exceed 16.")
  19. .Matches(@"[A-Z]+").WithMessage("Your password must contain at least one uppercase letter.")
  20. .Matches(@"[a-z]+").WithMessage("Your password must contain at least one lowercase letter.")
  21. .Matches(@"[0-9]+").WithMessage("Your password must contain at least one number.")
  22. .Matches(@"[\@\!\?\*\.]+").WithMessage("Your password must contain at least one (@!? *.).");
  23. RuleFor(_ => _.ConfirmPassword).Equal(_ => _.Password).WithMessage("ConfirmPassword must equal Password");
  24. public Func<object, string, Task<IEnumerable<string>>> ValidateValue => async (model, propertyName) =>
  25. var result = await ValidateAsync(ValidationContext<RegistrationVM>.CreateWithOptions((RegistrationVM)model, x => x.IncludeProperties(propertyName)));
  26. if (result.IsValid)
  27. return Array.Empty<string>();
  28. return result.Errors.Select(e => e.ErrorMessage);
  29. private async Task<bool> UniqueEmail(string email)
  30. if (string.IsNullOrEmpty(email))
  31. return true;
  32. string url = $"/api/user/unique-user-email?email={email}";
  33. var response = await _httpClient.GetAsync(url);
  34. response.EnsureSuccessStatusCode();
  35. var content = await response.Content.ReadAsStringAsync();
  36. return JsonSerializer.Deserialize<bool>(content);
  37. catch (Exception e)
  38. 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.

BlazorWasm_Project/Pages/Accounts/Registration.razor:(C# Part)


  1. @code {
  2. RegistrationVM registrationModel = new RegistrationVM();
  3. RegistrationValidationVm registrationValidator;
  4. MudForm form;
  5. string APIErrorMessage = string.Empty;
  6. protected override Task OnInitializedAsync()
  7. registrationValidator = new RegistrationValidationVm(_httpClient);
  8. return base.OnInitializedAsync();
  9. private async Task RegisterAsync()
  10. await form.Validate();
  11. if (form.IsValid)
  12. // invoke register API call.
  13. var jsonPayload = JsonSerializer.Serialize(registrationModel);
  14. var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
  15. var response = await _httpClient.PostAsync("/api/user/register", requestContent);
  16. if(response.StatusCode == System.Net.HttpStatusCode.BadRequest)
  17. var errors = await response.Content
  18. .ReadFromJsonAsync<Dictionary<string, List<string>>>();
  19. if(errors.Count > 0)
  20. foreach (var item in errors)
  21. foreach (var errorMessage in item.Value)
  22. APIErrorMessage = $"{errorMessage} | ";
  23. else if(response.StatusCode == System.Net.HttpStatusCode.OK)
  24. _navigationManager.NavigateTo("/registration-confirmation");
  25. APIErrorMessage = "Failed To Register User Please Try After SomeTime";
  • (Line: 12) Passing the HttpClient instance to the 'RegistrationValidationVm'.
18.PNG
In the next article, we will implement user login functionality and generate a JWT authentication token.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on the.NET7 Blazor WebAssembly JWT Authentication. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK