Custom AuthenticationStateProvider in ASP.NET Blazor

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        // user is anonymous
        // ClaimsIdentity claimsIdentity = new ClaimsIdentity();
        
        // user is authenticated
        ClaimsIdentity claimsIdentity = new ClaimsIdentity("test");
        claimsIdentity.AddClaim(new Claim("AccessUserPages","true"));

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
        AuthenticationState authenticationState = new AuthenticationState(claimsPrincipal);
        return await Task.FromResult(authenticationState);
    }
}

Program.cs

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();

Index,razor

@page "/"
@using System.Security.Claims
@inject AuthenticationStateProvider AuthenticationStateProvider

<div>
    Authentication : @authMessage
</div>

<div>
    <h5>Claims</h5>
    @if (claims.Any())
    {
        <ul>
            @foreach (var claim in claims)
            {
                <li>@claim.Type : @claim.Value</li>
            }
        </ul>   
    }
</div>

@code
{
    private string authMessage;
    private IEnumerable<Claim> claims = Enumerable.Empty<Claim>();


    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            authMessage = "user is authenticated";
            claims = user.Claims;
        }
        else
        {
            authMessage = "user is not authenticated";
        }
    }
}

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-6.0#authenticationstateprovider-service

Configure ASP.NET Core Data Protection to Persist Keys To DbContext

PersistKeysToDbContext

dotnet add package Microsoft.AspNetCore.DataProtection.EntityFrameworkCore

Add using Microsoft.AspNetCore.DataProtection; to Startup.cs

builder.Services.AddDataProtection()
    .PersistKeysToDbContext<SampleDbContext>();

The preceding code stores the keys in the configured database. The database context being used must implement IDataProtectionKeyContextIDataProtectionKeyContext exposes the property DataProtectionKeys

public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;

References
https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-6.0
https://stackoverflow.com/questions/57216907/how-to-fix-idataprotectionbuilder-does-not-contain-a-definition-for-persist

Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core

Antiforgery middleware is added to the Dependency injection container when one of the following APIs is called in Program.cs:

The FormTagHelper injects antiforgery tokens into HTML form elements. The following markup in a Razor file automatically generates antiforgery tokens:

<form method="post">
    <!-- ... -->
</form>

Explicitly add an antiforgery token to a <form> element without using Tag Helpers with the HTML helper @Html.AntiForgeryToken:

<form asp-action="Index" asp-controller="Home" method="post">
    @Html.AntiForgeryToken()

    <!-- ... -->
</form>

In each of the preceding cases, ASP.NET Core adds a hidden form field similar to the following example:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">

Configure antiforgery with AntiforgeryOptions

Customize AntiforgeryOptions in Program.cs:

builder.Services.AddAntiforgery(options =>
{
    // Set Cookie properties using CookieBuilder properties†.
    options.FormFieldName = "AntiforgeryFieldname";
    options.HeaderName = "X-CSRF-TOKEN-HEADERNAME";
    options.SuppressXFrameOptionsHeader = false;
});

References
https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-6.0
https://stackoverflow.com/questions/51248053/antiforgery-cookie-in-asp-net-core-2-0

Configure Many-to-Many Relationships using Fluent API in Entity Framework Core

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }
}
public class StudentCourse
{
    public int StudentId { get; set; }
    public Student Student { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    public IList<StudentCourse> StudentCourses { get; set; }
}
public class SchoolContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=EFCore-SchoolDB;Trusted_Connection=True");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<StudentCourse>().HasKey(sc => new { sc.StudentId, sc.CourseId });
    }
    
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<StudentCourse> StudentCourses { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-many-to-many-relationship-in-ef-core.aspx

Configure One-to-One Relationships using Fluent API in Entity Framework Core

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOne<StudentAddress>(s => s.Address)
            .WithOne(ad => ad.Student)
            .HasForeignKey<StudentAddress>(ad => ad.AddressOfStudentId);
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<StudentAddress> StudentAddresses { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public StudentAddress Address { get; set; }
}

public class StudentAddress
{
    public int StudentAddressId { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public int AddressOfStudentId { get; set; }
    public Student Student { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx
https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

Configure One-to-Many Relationships using Fluent API in Entity Framework Core

 

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOne<Grade>(s => s.Grade)
            .WithMany(g => g.Students)
            .HasForeignKey(s => s.CurrentGradeId);
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Grade> Grades { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CurrentGradeId { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}

References
https://www.entityframeworktutorial.net/efcore/configure-one-to-many-relationship-using-fluent-api-in-ef-core.aspx
https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

Entity Framework Core tools reference – .NET Core CLI

Installing the tools

dotnet ef can be installed as either a global or local tool.

dotnet tool install --global dotnet-ef
dotnet new tool-manifest # if you are setting up this repo
dotnet tool install --local dotnet-ef

Before you can use the tools on a specific project, you’ll need to add the Microsoft.EntityFrameworkCore.Design package to it.

dotnet add package Microsoft.EntityFrameworkCore.Design

Update the tools

Use dotnet tool update --global dotnet-ef to update the global tools to the latest available version. If you have the tools installed locally in your project use dotnet tool update dotnet-ef. Install a specific version by appending --version <VERSION> to your command. See the Update section of the dotnet tool documentation for more details.

Usefull Commands

dotnet ef database drop

Deletes the database.

dotnet ef database update

Updates the database to the last migration or to a specified migration.

dotnet ef dbcontext info

Gets information about a DbContext type.

dotnet ef dbcontext list

Lists available DbContext types.

dotnet ef dbcontext optimize

Generates a compiled version of the model used by the DbContext. Added in EF Core 6.

dotnet ef dbcontext scaffold

Generates code for a DbContext and entity types for a database. In order for this command to generate an entity type, the database table must have a primary key.

dotnet ef dbcontext script

Generates a SQL script from the DbContext. Bypasses any migrations.

dotnet ef migrations add

Adds a new migration.

dotnet ef migrations bundle

Creates an executable to update the database.

dotnet ef migrations list

Lists available migrations.

dotnet ef migrations remove

Removes the last migration, rolling back the code changes that were done for the latest migration.

dotnet ef migrations script

Generates a SQL script from migrations.

Reverting a Migration

Suppose you changed your domain class and created the second migration named MySecondMigration using the add-migration command and applied this migration to the database using the Update command. But, for some reason, you want to revert the database to the previous state. In this case, use the update-database <migration name> command to revert the database to the specified previous migration snapshot.

dotnet ef database update MyFirstMigration

The above command will revert the database based on a migration named MyFirstMigration and remove all the changes applied for the second migration named MySecondMigration. This will also remove MySecondMigration entry from the __EFMigrationsHistory table in the database.

Note: This will not remove the migration files related to MySecondMigration. Use the remove commands to remove them from the project.

References
https://docs.microsoft.com/en-us/ef/core/cli/dotnet

Configure PostgreSQL Entity Framework for ASP.NET using Npgsql

Install Required Packages

dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

Install dotnet-ef

Install it locally or globally.

Local

dotnet new tool-manifest # if you are setting up this repo
dotnet tool install --local dotnet-ef

Global

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

Defining a DbContext

using Microsoft.EntityFrameworkCore;

namespace BlazorApp1;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345");
    }

    public DbSet<Person> People { get; set; }
}

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Create Migration

dotnet ef migrations add InitialCreate

Apply to Database

dotnet ef database update

or

dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate --connection your_connection_string

Program.cs

builder.Services.AddDbContext<AppDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("AppDbContext")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

References
https://www.npgsql.org/efcore/index.html
https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-6.0&tabs=visual-studio
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations?view=aspnetcore-6.0
https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
https://docs.microsoft.com/en-us/ef/core/cli/dotnet

Handling Form submission with Validation in Blazor

The EditForm component is Blazor’s approach to managing user-input in a way that makes it easy to perform validation against user input. It also provides the ability to check if all validation rules have been satisfied, and present the user with validation errors if they have not.

The EditForm provides the following callbacks for handling form submission:

  • Use OnValidSubmit to assign an event handler to run when a form with valid fields is submitted.
  • Use OnInvalidSubmit to assign an event handler to run when a form with invalid fields is submitted.
  • Use OnSubmit to assign an event handler to run regardless of the form fields’ validation status. The form is validated by calling EditContext.Validate in the event handler method. If Validate returns true, the form is valid.
@page "/"
@using System.ComponentModel.DataAnnotations

<EditForm Model="@person" OnSubmit="FormSubmit">
    <DataAnnotationsValidator/>
    <ValidationSummary/>
    <div class="mb-3">
        <label for="inputFirstName" class="form-label">First Name</label>
        <InputText @bind-Value="person.FirstName" class="form-control" id="inputFirstName"></InputText>
    </div>
    <div class="mb-3">
        <label for="inputLastName" class="form-label">Last Name</label>
        <InputText @bind-Value="person.LastName" class="form-control" id="inputLastName"></InputText>
    </div>
    <div class="mb-3">
        <label for="inputAge" class="form-label">Age</label>
        <InputNumber @bind-Value="person.Age" class="form-control" id="inputAge"></InputNumber>
    </div>

    <input type="submit" class="btn btn-primary" value="Save"/>
</EditForm>

<div>Form validation : @isFormValid</div>

@code
{

    private Person person = new();
    private bool isFormValid = false;

    public class Person
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "First Name is empty")]
        public string? FirstName { get; set; }

        [Required(ErrorMessage = "Last Name is empty")]
        public string? LastName { get; set; }

        [Required]
        [Range(0, 150, ErrorMessage = "Age is not in range")]
        public int Age { get; set; } = 36;
    }

    private void FormSubmit(EditContext editContext)
    {
        if (editContext.Validate())
        {
            isFormValid = true;
        }
    }
}

You can use ValidationMessage Component instead of ValidationSummary Component to show error message for each field.

<EditForm Model="@person" OnSubmit="FormSubmit">
    <DataAnnotationsValidator/>
    <div class="mb-3">
        <label for="inputFirstName" class="form-label">First Name</label>
        <InputText @bind-Value="person.FirstName" class="form-control" id="inputFirstName"></InputText>
        <ValidationMessage For="() => person.FirstName"></ValidationMessage>
    </div>
    <div class="mb-3">
        <label for="inputLastName" class="form-label">Last Name</label>
        <InputText @bind-Value="person.LastName" class="form-control" id="inputLastName"></InputText>
        <ValidationMessage For="() => person.LastName"></ValidationMessage>
    </div>
    <div class="mb-3">
        <label for="inputAge" class="form-label">Age</label>
        <InputNumber @bind-Value="person.Age" class="form-control" id="inputAge"></InputNumber>
        <ValidationMessage For="() => person.Age"></ValidationMessage>
    </div>

    <input type="submit" class="btn btn-primary" value="Save"/>
</EditForm>

 

References
https://blazor-university.com/forms/handling-form-submission/
https://docs.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-6.0

Navigating in Blazor using the NavLink component

Use a NavLink component in place of HTML hyperlink elements (<a>) when creating navigation links. A NavLink component behaves like an <a> element, except it toggles an active CSS class based on whether its href matches the current URL. The active class helps a user understand which page is the active page among the navigation links displayed. Optionally, assign a CSS class name to NavLink.ActiveClass to apply a custom CSS class to the rendered link when the current route matches the href.

<nav class="flex-column">
    <div class="nav-item px-3">
        <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
            <span class="oi oi-home" aria-hidden="true"></span> Home
        </NavLink>
    </div>
    <div class="nav-item px-3">
        <NavLink class="nav-link" href="counter">
            <span class="oi oi-plus" aria-hidden="true"></span> Counter
        </NavLink>
    </div>
    <div class="nav-item px-3">
        <NavLink class="nav-link" href="fetchdata">
            <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
        </NavLink>
    </div>
</nav>

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-6.0#navlink-and-navmenu-components
https://blazor-university.com/routing/navigating-our-app-via-html/