How does authentication state flow from ASP.NET Core's cookie/JWT authentication into a Blazor component via AuthenticationStateProvider?
Short answer
AuthenticationStateProvider is the abstraction Blazor components use (via the component or @attribute [Authorize]) to access the current user's authentication state -- for Blazor Server, this integrates directly with the same HttpContext.User established by ASP.NET Core's…
Advertisement
AModel answer
AuthenticationStateProvider is the abstraction Blazor components use (via the <AuthorizeView> component or @attribute [Authorize]) to access the current user's authentication state -- for Blazor Server, this integrates directly with the same HttpContext.User established by ASP.NET Core's standard authentication middleware during the initial page request; for Blazor WebAssembly, a custom AuthenticationStateProvider typically manages a token stored client-side since there's no persistent server-side HttpContext to rely on.
@page "/profile"
@attribute [Authorize]
<AuthorizeView>
<Authorized>
<p>Welcome, @context.User.Identity.Name</p>
</Authorized>
<NotAuthorized>
<p>Please log in.</p>
</NotAuthorized>
</AuthorizeView>Real-world example
A Blazor Server admin page uses [Authorize(Roles="Admin")] at the component level, seamlessly reusing the exact same cookie-based identity already established by ASP.NET Core Identity for the rest of the application's MVC pages.
Likely follow-ups
- How does a custom AuthenticationStateProvider work differently for Blazor WebAssembly's token-based auth?
- How do you access the current user's claims imperatively inside a component's code?
Related topics