perfectdev.BlazorAuth 1.0.5

dotnet add package perfectdev.BlazorAuth --version 1.0.5
                    
NuGet\Install-Package perfectdev.BlazorAuth -Version 1.0.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="perfectdev.BlazorAuth" Version="1.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="perfectdev.BlazorAuth" Version="1.0.5" />
                    
Directory.Packages.props
<PackageReference Include="perfectdev.BlazorAuth" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add perfectdev.BlazorAuth --version 1.0.5
                    
#r "nuget: perfectdev.BlazorAuth, 1.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package perfectdev.BlazorAuth@1.0.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=perfectdev.BlazorAuth&version=1.0.5
                    
Install as a Cake Addin
#tool nuget:?package=perfectdev.BlazorAuth&version=1.0.5
                    
Install as a Cake Tool

BlazorAuth

Blazor Auth component work on browser local storage authentification token.

Install BlazorAuth in your app

Change the rendering mode of the Blazor components render-mode="Server" (in _Host.cshtml)

Add new parameters to appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "AuthConnection": "Data Source=Data/auth.db;Pooling=True;"
  },
  "AuthTokenDaysExpired": 1
}
ConnectionStrings > AuthConnection = 'Connection string for your database'
AuthTokenDaysExpired = [Days before token expiration time]

Implementing the service in your application (Program.cs).

Configure DataProtection service:

builder.Services.AddDataProtection().UseCryptographicAlgorithms(
    new AuthenticatedEncryptorConfiguration {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    });

Add connection string for Auth-database:

var authConnectionString = builder.Configuration.GetConnectionString("AuthConnection") 
    ?? throw new InvalidOperationException("Connection string 'AuthConnection' not found.");

Extract AuthTokenDaysExpired parameter value from appsettings.json:

int.TryParse(builder.Configuration["AuthTokenDaysExpired"], out var authTokenDaysExpired);

Implementing the context of your database (input your assembly):

builder.Services.AddDbContext<AuthContext>(options => options.UseSqlite(authConnectionString), o => o.MigrationsAssembly("YourAssembly"))
                                                     .LogTo(Console.WriteLine, LogLevel.Information)
                                                     .EnableSensitiveDataLogging()
                                                     .EnableDetailedErrors());

You need to create a migration of the AuthContext tables:

Add-Migration AuthTables -context AuthContext
Update-Database -context AuthContext

Implementing the HttpContextAccessor:

builder.Services.AddHttpContextAccessor();

Implementing the BlazoredLocalStorage:

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<HttpContextAccessor>();

Integrate the ClientStorageService with your prefix (optional):

builder.Services.AddScoped<IClientStorageService, ClientStorageService>(x => 
    new ClientStorageService(x.GetRequiredService<ILocalStorageService>(), 
    "YourAppPrefix"));

Integrate the BlazorAuth authentication service with all dependencies into your application:

builder.Services.AddScoped<IAuthService, AuthService>(x => new AuthService(
                                                          x.GetRequiredService<ILocalStorageService>(),
                                                          x.GetRequiredService<HttpContextAccessor>(),
                                                          x.GetRequiredService<AuthContext>(),
                                                          authTokenDaysExpired));

Use in Blazor components

Implement dependencies in the component:

@using BlazorAuth;

@inject IClientStorageService ClientStorage
@inject IAuthService Auth

Override the OnInitializedAsync method in your component:

protected override async Task OnInitializedAsync() {
    await Auth.AutoLogon();
    ...
    await base.OnInitializedAsync();
}

await Auth.AutoLogon() checks for the presence of an open session on the client's IP and the presence of an active authentication token in the local browser storage (checks for expiration)

Example Logon method call:

if (!Auth.IsAuthorized) {
    await Auth.Logon(new BlazorAuth.Models.UserModel {
        Email = "your email",
        PasswordHash = "raw password (not hash!)"
    });
    await Auth.AutoLogon();
}

An example of the use of the Blazor component in the markup:

@using BlazorAuth;

@inject IClientStorageService ClientStorage
@inject IAuthService Auth

<div class="top-row ps-3 navbar navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="">BlazorServerApp</a>
        <button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
</div>

@if (Auth.IsAuthorized) {
    <div class="@NavMenuCssClass nav-scrollable" @onclick="ToggleNavMenu">
        <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>
    </div>
}

@code {
    private bool collapseNavMenu = true;

    private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;

    private void ToggleNavMenu() {
        collapseNavMenu = !collapseNavMenu;
    }

    protected override async Task OnInitializedAsync() {
        await Auth.AutoLogon();
        await base.OnInitializedAsync();
    }
}
Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.5 748 6/2/2023
1.0.4 731 5/24/2023
1.0.3 695 5/24/2023
1.0.2 740 5/24/2023
1.0.1 731 5/11/2023
1.0.0 718 5/11/2023