Skip to main content

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

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)

(Step 2)

(Step 3)

Setup MudBlazor:

Install the MudBlazor library.

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'.

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:
@inherits LayoutComponentBase

<MudThemeProvider />
<MudDialogProvider />
<MudSnackbarProvider />

<MudLayout>
    <MudAppBar Color="Color.Primary" Fixed="false">
       JWT Auth Demo
    </MudAppBar>
    <MudMainContent>
        @Body
    </MudMainContent>
</MudLayout>

Install FluentValidation Library:

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

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:
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':

Now to add FluentValidation rules on 'RegistrationVm' let's create a model like 'RegistrationValidationVm' in the 'ViewModels/Account' folder.
ViewModels/Account/RegistrationValidationVm.cs:
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'.
_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)
@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.
Shared/MainLayout.razor:
@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:

Let's create .NET7 API project using Visual Studio 2022
(Step 1)

(Step 2)

(Step 3)

(Step 4)

Install Entity FrameworkCore NuGet Package:

Let's install the entity framework core into our API project.

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

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:
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.
API_Project/Data/MyWorldDbContext.cs:
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'.
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:
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).
API_Project/Services/IUserService.cs:
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.
API_Project/Services/UserService.cs:
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'
API_Project/Program.cs:
builder.Services.AddScoped<IUserService, UserService>();
Let's create the user registration post endpoint.
API_Project/Controllers/UserController.cs:
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:

First, enable cors in the API project to allow Blazor WebAssembly to consume API endpoints.

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)
@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");
            }
            else
            {
                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:
@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)

(Step 2)

(Step 3)

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:
bool CheckUserUniqueEmail(string email);
Now implement the 'CheckUserUniqueEmail' method in 'UserService.cs'.
API_Project/Services/UserServices.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'.
API_Project/Controllers/UserController.cs:
[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.
BlazorWasm/ViewModels/Accounts/RegistrationValidationVm.cs:
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;
            }
            try
            {
                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.
BlazorWasm_Project/Pages/Accounts/Registration.razor:(C# Part)
@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");
            }
            else
            {
                APIErrorMessage = "Failed To Register User Please Try After SomeTime";
            }
        }
    }
}
  • (Line: 12) Passing the HttpClient instance to the 'RegistrationValidationVm'.

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.

Refer:



Follow Me:

Comments

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually