Say you’re building the internal app for Summit Ridge Supply, a plumbing-supply distributor in Boise, Idaho. Every staff member should see the Orders page after signing in, but only managers may open Payroll.
That’s the job of Blazor authentication in a .NET 10 Blazor Web App: ASP.NET Core Identity signs people in, AuthenticationStateProvider tells each component who they are, and [Authorize] locks the pages. We’ll build it with local accounts on SQLite.
Here’s what we’re building:

- Local accounts from the
--auth Individualtemplate (ASP.NET Core Identity + SQLite) <AuthorizeView>for signed-in content and[Authorize]on the Orders page- A seeded Manager role guarding Payroll with
[Authorize(Roles = "Manager")] - A My account page that reads the current user through
AuthenticationStateProvider
Before You Start with Blazor Authentication
You need the .NET 10 SDK (I used 10.0.402) and an editor; I use VS Code. If you aren’t sure what’s installed, check your .NET version first. No Azure, Entra ID or SQL Server is needed.
If pages, routing and @code blocks are new to you, my Blazor tutorial for beginners covers them. Here are the two test accounts and what each one may open:
| Account | How it’s created | Role | Orders | Payroll |
|---|---|---|---|---|
| alicia.morgan@example.com | Registered through the Register page | none | Yes | No |
| derek.nolan@example.com | Seeded in code (SeedData.cs) | Manager | Yes | Yes |
| (not signed in) | – | – | No | No |
The Orders page lists three open sales orders for Idaho customers, due 12/04/2026 through 12/09/2026. Payroll shows hourly rates for three staff members.
How Does Authentication Work in a Blazor Web App?
Blazor doesn’t sign anyone in by itself. ASP.NET Core Identity checks the password and writes an auth cookie. Blazor then wraps that user in an AuthenticationState and serves it from an AuthenticationStateProvider.
AddCascadingAuthenticationState() cascades a Task<AuthenticationState> to every component. <AuthorizeView>, [Authorize] and your own code all read from it. It works the same in static SSR and interactive pages; my Blazor render modes guide explains those modes.
Note: this is cookie sign-in for the app’s own pages. If a separate API needs tokens, that’s JWT authentication in ASP.NET Core, a different setup.
Step 1: Create the Blazor Web App with Individual Accounts
Create the app from the Blazor Web App template with local accounts:
dotnet new blazor --auth Individual -o W15BlazorAuth
cd W15BlazorAuth
From the command line, this template uses SQLite. It ships Data/app.db (118,784 bytes) with the CreateIdentitySchema migration already applied, so I didn’t have to run dotnet ef database update. Visual Studio’s version of the template uses SQL Server instead.
I deleted the Counter, Weather and Auth sample pages plus appsettings.Development.json, and set the http profile to port 5930:
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5930",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:5931;http://localhost:5930",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
The project file is the template’s, with the .NET 10 Identity and EF Core SQLite packages at 10.0.13:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>aspnet-W15BlazorAuth-40ff3cac-e1ff-448a-805c-b19f3dd4c2da</UserSecretsId>
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
</PropertyGroup>
<ItemGroup>
<None Update="Data\app.db" CopyToOutputDirectory="PreserveNewest" ExcludeFromSingleFile="true" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="10.0.13" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.13" PrivateAssets="all" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.13" />
</ItemGroup>
</Project>
The SQLite connection string lives in appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "DataSource=Data/app.db;Cache=Shared"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Checkpoint: when you start it with dotnet run, you’ll see Now listening on: http://localhost:5930, and your nav menu shows Register and Login.
Step 2: See What the Template Wires Up for Authentication
Open Program.cs and you’ll find the Blazor half of the setup in these two lines:
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
Below them, AddAuthentication(...).AddIdentityCookies() adds the cookie schemes, and AddIdentityCore<ApplicationUser> sets RequireConfirmedAccount = true. The provider is registered with AddScoped, one per circuit (see DI lifetimes in ASP.NET Core).

Here’s the provider the template generated. It extends RevalidatingServerAuthenticationStateProvider and re-checks the user’s security stamp every 30 minutes while a circuit is open:
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using W15BlazorAuth.Data;
namespace W15BlazorAuth.Components.Account;
// This is a server-side AuthenticationStateProvider that revalidates the security stamp for the connected user
// every 30 minutes an interactive circuit is connected.
internal sealed class IdentityRevalidatingAuthenticationStateProvider(
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory,
IOptions<IdentityOptions> options)
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
{
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);
protected override async Task<bool> ValidateAuthenticationStateAsync(
AuthenticationState authenticationState, CancellationToken cancellationToken)
{
// Get the user manager from a new scope to ensure it fetches fresh data
await using var scope = scopeFactory.CreateAsyncScope();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
return await ValidateSecurityStampAsync(userManager, authenticationState.User);
}
private async Task<bool> ValidateSecurityStampAsync(UserManager<ApplicationUser> userManager, ClaimsPrincipal principal)
{
var user = await userManager.GetUserAsync(principal);
if (user is null)
{
return false;
}
else if (!userManager.SupportsUserSecurityStamp)
{
return true;
}
else
{
var principalStamp = principal.FindFirstValue(options.Value.ClaimsIdentity.SecurityStampClaimType);
var userStamp = await userManager.GetSecurityStampAsync(user);
return principalStamp == userStamp;
}
}
}
The user and database classes are empty on purpose. You’d add profile columns to ApplicationUser; the EF Core tutorial explains the DbContext side:
using Microsoft.AspNetCore.Identity;
namespace W15BlazorAuth.Data;
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace W15BlazorAuth.Data;
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options)
{
}
The last piece is a placeholder email sender. It sends nothing, and you’ll see why that matters in the next step:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using W15BlazorAuth.Data;
namespace W15BlazorAuth.Components.Account;
// Remove the "else if (EmailSender is IdentityNoOpEmailSender)" block from RegisterConfirmation.razor after updating with a real implementation.
internal sealed class IdentityNoOpEmailSender : IEmailSender<ApplicationUser>
{
private readonly IEmailSender emailSender = new NoOpEmailSender();
public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) =>
emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by <a href='{confirmationLink}'>clicking here</a>.");
public Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) =>
emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password by <a href='{resetLink}'>clicking here</a>.");
public Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) =>
emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password using the following code: {resetCode}");
}
Step 3: Register and Confirm a Test User
Run the app, open /Account/Register, and register alicia.morgan@example.com with a password like Orders-2026!.
Since no real email sender exists, the template shows the confirmation link on the page instead of emailing it. That’s the development flow:

Before clicking it, I tried to log in as Alicia. The Login page answered “Error: Invalid login attempt.” because the account wasn’t confirmed yet.
After I opened the link, the ConfirmEmail page said:

Checkpoint: logging in as Alicia now works and the nav menu shows her email and Logout. The Identity pages are static SSR forms, like the ones in my Blazor form validation walkthrough.
Step 4: Show or Hide Content with Blazor AuthorizeView
Replace Components/Pages/Home.razor with this. <Authorized> renders for signed-in users, <NotAuthorized> for everyone else, and context.User is the current user:
@page "/"
<PageTitle>Staff portal</PageTitle>
<h1>Summit Ridge Supply staff portal</h1>
<AuthorizeView>
<Authorized>
<p>Welcome back, @context.User.Identity?.Name.</p>
<p><a href="orders">Open orders</a></p>
</Authorized>
<NotAuthorized>
<p>Log in with your work account to see today's orders.</p>
<p><a href="Account/Login">Log in</a></p>
</NotAuthorized>
</AuthorizeView>
<AuthorizeView Roles="Manager">
<div class="alert alert-info">Manager tools: <a href="payroll">Payroll</a></div>
</AuthorizeView>
Signed out, the page shows the log-in prompt:

Signed in as Alicia, it greets her by name. I also wrapped the new nav links in NavMenu.razor with <AuthorizeView>, so Orders and My account only appear after login:
<AuthorizeView>
<div class="nav-item px-3">
<NavLink class="nav-link" href="orders">
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Orders
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="me">
<span class="bi bi-lock-nav-menu" aria-hidden="true"></span> My account
</NavLink>
</div>
</AuthorizeView>
<AuthorizeView Roles="Manager">
<div class="nav-item px-3">
<NavLink class="nav-link" href="payroll">
<span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span> Payroll
</NavLink>
</div>
</AuthorizeView>

Important: AuthorizeView only hides markup. Anyone can still type /orders in the address bar, so the page itself needs [Authorize]. It’s a regular component, so it also works inside your own Blazor components.
Step 5: Protect a Blazor Page with the [Authorize] Attribute
Create Components/Pages/Orders.razor. The @attribute [Authorize] line means signed-in users only:
@page "/orders"
@using System.Globalization
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
<PageTitle>Orders</PageTitle>
<h1>Open orders</h1>
<p>Signed in as <strong>@userName</strong></p>
<table class="table">
<thead><tr><th>Order</th><th>Customer</th><th>Ship to</th><th>Due</th><th>Total</th></tr></thead>
<tbody>
@foreach (var o in orders)
{
<tr>
<td>@o.Number</td><td>@o.Customer</td><td>@o.City</td>
<td>@o.Due.ToString("MM/dd/yyyy", Us)</td><td>@o.Total.ToString("C", Us)</td>
</tr>
}
</tbody>
</table>
@code {
private static readonly CultureInfo Us = CultureInfo.GetCultureInfo("en-US");
private string? userName;
private readonly (string Number, string Customer, string City, DateOnly Due, decimal Total)[] orders =
[
("SO-10421", "Cascade Plumbing", "Boise, ID", new(2026, 12, 4), 1284.50m),
("SO-10422", "Treasure Valley HVAC", "Nampa, ID", new(2026, 12, 7), 642.18m),
("SO-10423", "Snake River Builders", "Twin Falls, ID", new(2026, 12, 9), 3915.00m),
];
[CascadingParameter]
private Task<AuthenticationState>? AuthState { get; set; }
protected override async Task OnInitializedAsync()
{
if (AuthState is not null)
{
var user = (await AuthState).User;
userName = user.Identity?.Name;
}
}
}
Signed out, I requested /orders with curl. The server answered before Blazor rendered anything:
302 http://localhost:5930/Account/Login?ReturnUrl=%2Forders
That’s a 302 to the login page with ReturnUrl, so the user lands back on Orders after logging in. For in-app navigation, the template’s RedirectToLogin component does the same with NavigationManager.NavigateTo.

After Alicia logs in, she’s sent straight back to her orders:
![Blazor Orders page protected by [Authorize] showing Signed in as alicia.morgan@example.com and three open orders with US dates and dollar totals](https://aspdotnethelp.com/wp-content/uploads/2026/11/blazor-authorize-orders-page-signed-in-user-name.png)
Checkpoint: the page shows “Signed in as alicia.morgan@example.com” and three orders, from $642.18 to $3,915.00.
Step 6: Add Roles to Blazor Authentication for a Manager-Only Page
The template doesn’t turn roles on. Add .AddRoles<IdentityRole>() to the Identity chain, then seed a Manager role and one manager account at startup in development. Here’s the whole Program.cs after both changes:
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using W15BlazorAuth.Components;
using W15BlazorAuth.Components.Account;
using W15BlazorAuth.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddIdentityCore<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Stores.SchemaVersion = IdentitySchemaVersions.Version3;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
await SeedData.AddManagerAsync(app.Services);
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseHttpsRedirection();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();
app.Run();
And Data/SeedData.cs. RoleManager creates the role once, and UserManager creates Derek with a confirmed email and adds him to it:
using Microsoft.AspNetCore.Identity;
namespace W15BlazorAuth.Data;
public static class SeedData
{
// Development only: one Manager account so the Payroll page can be tested
public static async Task AddManagerAsync(IServiceProvider services)
{
using var scope = services.CreateScope();
var roles = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!await roles.RoleExistsAsync("Manager"))
await roles.CreateAsync(new IdentityRole("Manager"));
const string email = "derek.nolan@example.com";
if (await users.FindByEmailAsync(email) is null)
{
var derek = new ApplicationUser { UserName = email, Email = email, EmailConfirmed = true };
await users.CreateAsync(derek, "Demo-Pass-2026!");
await users.AddToRoleAsync(derek, "Manager");
}
}
}

Note: a hard-coded password is fine on a dev box only. In production, read it from configuration (see appsettings per environment) or create managers by hand.
Now the Payroll page. Roles takes a comma-separated list, and role names are case-sensitive:
@page "/payroll"
@using System.Globalization
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles = "Manager")]
<PageTitle>Payroll</PageTitle>
<h1>Payroll</h1>
<p class="text-secondary">Visible to the Manager role only.</p>
<table class="table">
<thead><tr><th>Employee</th><th>Position</th><th>Hourly rate</th><th>Hours (week of 11/30/2026)</th></tr></thead>
<tbody>
@foreach (var p in staff)
{
<tr><td>@p.Name</td><td>@p.Position</td><td>@p.Rate.ToString("C", Us)</td><td>@p.Hours</td></tr>
}
</tbody>
</table>
@code {
private static readonly CultureInfo Us = CultureInfo.GetCultureInfo("en-US");
private readonly (string Name, string Position, decimal Rate, int Hours)[] staff =
[
("Alicia Morgan", "Inside sales", 24.50m, 40),
("Tyler Brooks", "Warehouse lead", 22.75m, 42),
("Jenna Morales", "Delivery driver", 21.00m, 38),
];
}
Alicia has no role, so /payroll sends her to /Account/AccessDenied: “You do not have access to this resource.”

Derek gets the page, plus the Payroll link that <AuthorizeView Roles="Manager"> adds to Home and the nav menu:

Checkpoint: Derek sees three rows at $24.50, $22.75 and $21.00 an hour; Alicia sees Access denied.
How Do You Get the Current User in Blazor?
There are two ways, and the Orders page already used the first: a [CascadingParameter] Task<AuthenticationState>. Await it, then read User.Identity?.Name. Microsoft’s docs recommend this for procedural logic.
The second is to inject AuthenticationStateProvider and call GetAuthenticationStateAsync(). I used it in Me.razor to list every claim, with long values cut to 8 characters:
@page "/me"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@inject AuthenticationStateProvider AuthProvider
<PageTitle>My account</PageTitle>
<h1>Who is signed in?</h1>
@if (user is not null)
{
<p id="summary">
Name: <strong>@user.Identity?.Name</strong> |
Authenticated: @user.Identity?.IsAuthenticated |
Type: @user.Identity?.AuthenticationType |
Manager: @user.IsInRole("Manager")
</p>
<table class="table table-sm" id="claims">
<thead><tr><th>Claim type</th><th>Value</th></tr></thead>
<tbody>
@foreach (var claim in user.Claims)
{
<tr><td>@claim.Type</td><td>@Shorten(claim.Value)</td></tr>
}
</tbody>
</table>
}
@code {
private System.Security.Claims.ClaimsPrincipal? user;
protected override async Task OnInitializedAsync()
{
var state = await AuthProvider.GetAuthenticationStateAsync();
user = state.User;
}
private static string Shorten(string value) => value.Length > 20 ? value[..8] + "..." : value;
}
Both run in OnInitializedAsync, which my Blazor component lifecycle post covers. Here’s Alicia’s page with 5 claims:

Derek’s list has one extra claim, the role. User.IsInRole("Manager") reads it:
| Claim type | Derek’s value |
|---|---|
.../claims/nameidentifier | fd3e35cf… |
.../claims/name | derek.no… |
.../claims/emailaddress | derek.no… |
AspNet.Identity.SecurityStamp | S5LOFYRN… |
.../claims/role | Manager |
amr | pwd |
The role claim’s full type is http://schemas.microsoft.com/ws/2008/06/identity/claims/role, which is ClaimTypes.Role.
Write a Custom AuthenticationStateProvider
You only need your own provider when the user doesn’t come from Identity, for example a kiosk badge reader. Override GetAuthenticationStateAsync(), and call NotifyAuthenticationStateChanged when the user changes. I ran it as a file-based app:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
var provider = new KioskAuthStateProvider();
provider.AuthenticationStateChanged += async task =>
Console.WriteLine($"Changed -> {(await task).User.Identity?.Name}");
var before = await provider.GetAuthenticationStateAsync();
Console.WriteLine($"Before: authenticated = {before.User.Identity?.IsAuthenticated}");
provider.SignIn("alicia.morgan@example.com");
var after = await provider.GetAuthenticationStateAsync();
Console.WriteLine($"After: {after.User.Identity?.Name} ({after.User.Identity?.AuthenticationType})");
class KioskAuthStateProvider : AuthenticationStateProvider
{
private ClaimsPrincipal user = new(new ClaimsIdentity()); // anonymous
public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
Task.FromResult(new AuthenticationState(user));
public void SignIn(string email)
{
user = new(new ClaimsIdentity([new Claim(ClaimTypes.Name, email)], "Kiosk"));
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
Output:
Before: authenticated = False
Changed -> alicia.morgan@example.com
After: alicia.morgan@example.com (Kiosk)

AuthorizeView and the cascading state subscribe to that event, which is why the UI re-renders. In a server app, register it scoped in place of the template’s provider:
builder.Services.AddScoped<AuthenticationStateProvider, KioskAuthStateProvider>();
Blazor Authentication with WebAssembly and Auto Render Modes
This app uses Interactive Server, so the provider runs on the server. With WebAssembly or Auto, the browser needs the user too. Since .NET 9, the server project serializes the state and the .Client project reads it:
// Server project, Program.cs
builder.Services.AddRazorComponents()
.AddInteractiveWebAssemblyComponents()
.AddAuthenticationStateSerialization();
// .Client project, Program.cs
builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthenticationStateDeserialization();
Only the name and role claims cross over by default. Set SerializeAllClaims to true in the serialization options if the browser needs the rest. My Blazor Server vs WebAssembly comparison helps you pick the mode.
Test the Blazor Authentication App
Here’s every check I ran with curl and headless Edge, so you can repeat them on your copy:
| Test | Who | Result |
|---|---|---|
GET /orders | signed out | 302 /Account/Login?ReturnUrl=%2Forders |
GET /payroll | signed out | 302 /Account/Login?ReturnUrl=%2Fpayroll |
| Log in before confirming | Alicia | Invalid login attempt. |
Open /orders | Alicia | Orders page, 3 rows |
Open /payroll | Alicia (no role) | Access denied |
Open /payroll | Derek (Manager) | Payroll page, 3 rows |
/me: IsInRole(“Manager”) | Alicia / Derek | False / True |
Troubleshooting Blazor Authentication
“Invalid login attempt” with the right password. The account isn’t confirmed and RequireConfirmedAccount is true. Use the dev link from Step 3, or plug in a real IEmailSender<ApplicationUser>.
“Failed to determine the https port for redirect” in the log. I got this warning because only the http profile runs. Start the https profile (port 5931 here) and it goes away.
“Authorization requires a cascading parameter of type Task<AuthenticationState>”. AddCascadingAuthenticationState() is missing from Program.cs. In .NET 8 and later, don’t wrap the router in the old <CascadingAuthenticationState> component.
[Authorize] on a child component does nothing. It only works on @page components reached through the router. Inside a page, use <AuthorizeView>.
A new role doesn’t apply. Role claims go into the cookie at sign-in, so a user you add to a role later has to log out and back in.
Where to Take It Next with Blazor Authentication
Swap IdentityNoOpEmailSender for a real sender so confirmation links arrive by email. Then add policies with [Authorize(Policy = ...)] for rules that don’t fit a role, like “store manager in Idaho”.
If the app grows an API for a mobile client, throttle the login endpoints with rate limiting in ASP.NET Core.
If this was your first secured Blazor app, these pick up where it stops:
- All Blazor tutorials on the site, in order
- ASP.NET Core tutorials for the server side
- Build a Web API with CRUD and EF Core
- Upgrade a .NET 8 Blazor app to .NET 10
Frequently Asked Questions
How do I get the current user in Blazor?
Add [CascadingParameter] private Task? AuthState { get; set; }, await it, and read User.Identity?.Name. You can also inject AuthenticationStateProvider and call GetAuthenticationStateAsync(). Both return a ClaimsPrincipal with the user’s claims and roles.
What is AuthenticationStateProvider in Blazor?
It’s the service Blazor asks for the current user. It returns an AuthenticationState through GetAuthenticationStateAsync() and raises AuthenticationStateChanged when the user changes. The Individual Accounts template registers IdentityRevalidatingAuthenticationStateProvider for Interactive Server apps.
What’s the difference between AuthorizeView and [Authorize] in Blazor?
[Authorize] protects a whole routable page, so the router redirects or denies the request. AuthorizeView only shows or hides markup inside a page. Use both: [Authorize] for security, AuthorizeView for the UI.
Which database does dotnet new blazor –auth Individual use?
The command-line template uses SQLite and includes Data/app.db with the Identity schema. Visual Studio’s template scaffolds Identity for SQL Server. See ASP.NET Core Blazor authentication and authorization on Microsoft Learn.
How do I write a custom AuthenticationStateProvider?
Inherit AuthenticationStateProvider, override GetAuthenticationStateAsync() and call NotifyAuthenticationStateChanged when the user changes. Register it scoped on the server or as a singleton in WebAssembly. Details are in ASP.NET Core Blazor authentication state.
Does Blazor authentication work with WebAssembly?
Yes. In a Blazor Web App on .NET 9 or later, call AddAuthenticationStateSerialization() in the server project and AddAuthenticationStateDeserialization() in the .Client project. Only name and role claims flow by default unless you set SerializeAllClaims.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…