Authentication is an important part of modern web application development. Most applications need to identify users, manage login sessions, protect sensitive information, and control access to different features.
In an ASP.NET Core application, authentication is commonly handled through ASP.NET Core Identity, cookie authentication, or an external identity provider. However, when a Blazor WebAssembly frontend communicates with an ASP.NET Core backend, developers need to make sure both parts of the application work with the same authenticated user.
This creates an important architectural question: How can a Blazor WebAssembly application share authentication with an ASP.NET Core API without implementing separate login systems?
The answer depends on how the application is hosted, how authentication is configured, and how the browser communicates with the backend.
In this article, we will explore how authentication works between Blazor WebAssembly and ASP.NET Core, understand cookie-based and token-based approaches, implement a practical authentication flow, and discuss security considerations for production applications.
Understanding Authentication Between Blazor WebAssembly and ASP.NET Core
Blazor WebAssembly applications execute inside the browser, while ASP.NET Core APIs execute on the server.
Because these applications run in different execution environments, they do not automatically share authentication state.
For example, imagine an employee management application with the following architecture:
Blazor WebAssembly handles the user interface.
ASP.NET Core Web API handles business operations.
ASP.NET Core Identity manages user accounts.
SQL Server stores user and application information.
When a user signs in, the backend establishes an authenticated session. However, the Blazor application also needs to understand whether the user is authenticated so it can display the appropriate pages, navigation options, and actions.
There are two important responsibilities here:
The backend must authenticate requests and enforce authorization.
The Blazor application must display the correct authentication state to the user.
These responsibilities are related, but they are not the same.
A Blazor component showing an authenticated user does not prove that the backend has authorized that user. Every protected API endpoint must perform its own authentication and authorization checks.
Understanding Different Authentication Approaches
There are multiple ways to share authentication between Blazor WebAssembly and ASP.NET Core.
The correct approach depends on whether the frontend and backend share the same origin and whether an external identity provider is involved.
Cookie-Based Authentication
Cookie authentication is a practical option when Blazor WebAssembly and ASP.NET Core are hosted under the same origin.
When a user signs in, the ASP.NET Core backend creates an authentication cookie and sends it to the browser.
The browser stores the cookie and automatically includes it in eligible requests to the same origin.
The ASP.NET Core application validates the cookie and identifies the user.
For example:
Blazor WebAssembly
|
| Login Request
|
v
ASP.NET Core API
|
| Validate Credentials
|
v
Authentication Cookie
|
v
Browser Stores Cookie
|
v
Future API Requests
|
v
ASP.NET Core Validates Cookie
This approach avoids exposing authentication tokens directly to JavaScript.
For browser-based applications, cookie authentication is generally a good choice when the application can use a secure same-origin architecture.
Token-Based Authentication
Token-based authentication is another approach, particularly when an application communicates with APIs hosted on separate origins or uses an external identity provider.
The user authenticates through an identity provider, and the application obtains an access token.
The Blazor application sends the token in the Authorization header when calling protected APIs.
For example:
GET /api/products HTTP/1.1
Host: api.example.com
Authorization: Bearer ACCESS_TOKEN
The backend validates the token and checks the user's permissions.
For production applications, OAuth 2.0 and OpenID Connect are preferred standards for this architecture.
Blazor WebAssembly supports authentication through the Microsoft.AspNetCore.Components.WebAssembly.Authentication library and OpenID Connect providers.
Comparing Cookie and Token Authentication
Feature | Cookie Authentication | Token Authentication |
|---|
Authentication storage | Browser-managed cookie | Access token |
Request handling | Browser sends eligible cookies automatically | Application sends bearer token |
JavaScript access | HttpOnly cookies are not accessible to JavaScript | Depends on token storage |
CSRF protection | Required for state-changing requests | Bearer-token requests require different CSRF considerations |
Cross-origin configuration | Requires careful cookie and CORS configuration | Requires appropriate CORS and token configuration |
Best suited for | Same-origin browser applications | API-based and distributed architectures |
For a same-origin Blazor application, cookie authentication is often simpler. For applications using multiple APIs and external identity providers, token-based authentication may be more appropriate.
Implementing Cookie Authentication Between Blazor WebAssembly and ASP.NET Core
Let's build a practical example using ASP.NET Core as the authentication authority and Blazor WebAssembly as the frontend.
Assume that the backend already has an ASP.NET Core Identity implementation responsible for validating user credentials.
We will use cookie authentication to maintain the user session.
Step 1: Configure Cookie Authentication in ASP.NET Core
Open the backend application's Program.cs file.
Configure authentication and authorization services:
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(
CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "Application.Auth";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy =
CookieSecurePolicy.Always;
options.Cookie.SameSite =
SameSiteMode.Lax;
options.LoginPath = "/account/login";
options.ExpireTimeSpan =
TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = 403;
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Let's understand some important settings.
Cookie.Name defines the authentication cookie name.
HttpOnly prevents JavaScript from reading the cookie directly.
SecurePolicy ensures that the cookie is transmitted over HTTPS.
SameSite controls when the browser sends the cookie in cross-site requests.
ExpireTimeSpan defines the authentication ticket lifetime.
The redirect event configuration is also important for APIs. Instead of redirecting an API request to an HTML login page, the application returns an HTTP 401 response.
This example demonstrates cookie configuration. In an application already using ASP.NET Core Identity, configure the existing Identity application cookie rather than registering a competing authentication scheme.
Step 2: Create a Login Endpoint
The backend needs an endpoint that authenticates the user and establishes the session.
When using ASP.NET Core Identity, the login operation should validate credentials through the configured SignInManager.
A simplified controller example is shown below:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/account")]
public class AccountController : ControllerBase
{
private readonly SignInManager<ApplicationUser>
_signInManager;
public AccountController(
SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
[HttpPost("login")]
public async Task<IActionResult> Login(
LoginRequest request)
{
var result = await _signInManager.PasswordSignInAsync(
request.Email,
request.Password,
request.RememberMe,
lockoutOnFailure: true);
if (!result.Succeeded)
{
return Unauthorized(
new { Message = "Invalid login credentials." });
}
return Ok(new
{
Message = "Login successful."
});
}
}
public record LoginRequest(
string Email,
string Password,
bool RememberMe);
The PasswordSignInAsync method validates the supplied credentials and establishes the authentication session when the login succeeds.
The authentication cookie is generated by the configured Identity cookie scheme.
In production, also handle account lockout, email confirmation, two-factor authentication, and antiforgery protection.
Step 3: Configure HttpClient in Blazor WebAssembly
The Blazor application needs to communicate with the backend API.
Register HttpClient in the client project's Program.cs file:
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp =>
new HttpClient
{
BaseAddress = new Uri(
builder.HostEnvironment.BaseAddress)
});
await builder.Build().RunAsync();
This example assumes that the frontend and backend share the same origin.
When the browser sends same-origin HTTP requests, eligible authentication cookies are included automatically.
For a separate API origin, configure the API base address and browser credentials appropriately. The backend must also use an explicit CORS policy that allows the frontend origin and credentials.
Step 4: Create an Authentication State Provider
The Blazor application needs to know whether the current user is authenticated.
For this purpose, Blazor provides the AuthenticationStateProvider abstraction.
We can create a custom provider that retrieves the current user's authentication information from the backend.
First, create a response model:
public class UserInfo
{
public bool IsAuthenticated { get; set; }
public string? Name { get; set; }
public List<string> Roles { get; set; } = new();
}
Next, create a protected backend endpoint:
[Authorize]
[HttpGet("me")]
public IActionResult GetCurrentUser()
{
return Ok(new UserInfo
{
IsAuthenticated = true,
Name = User.Identity?.Name,
Roles = User.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value)
.ToList()
});
}
The endpoint returns information about the currently authenticated user.
Now create a custom authentication state provider in the Blazor WebAssembly project:
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using System.Net.Http.Json;
public class CustomAuthenticationStateProvider
: AuthenticationStateProvider
{
private readonly HttpClient _httpClient;
public CustomAuthenticationStateProvider(
HttpClient httpClient)
{
_httpClient = httpClient;
}
public override async Task<AuthenticationState>
GetAuthenticationStateAsync()
{
try
{
var userInfo = await _httpClient
.GetFromJsonAsync<UserInfo>("api/account/me");
if (userInfo == null ||
!userInfo.IsAuthenticated)
{
return AnonymousState();
}
var claims = new List<Claim>
{
new Claim(
ClaimTypes.Name,
userInfo.Name ?? string.Empty)
};
claims.AddRange(userInfo.Roles.Select(role =>
new Claim(ClaimTypes.Role, role)));
var identity = new ClaimsIdentity(
claims,
"ServerAuthentication");
return new AuthenticationState(
new ClaimsPrincipal(identity));
}
catch
{
return AnonymousState();
}
}
private static AuthenticationState AnonymousState()
{
return new AuthenticationState(
new ClaimsPrincipal(
new ClaimsIdentity()));
}
public void NotifyAuthenticationChanged(
ClaimsPrincipal user)
{
NotifyAuthenticationStateChanged(
Task.FromResult(
new AuthenticationState(user)));
}
}
This provider requests the current user information from the backend and creates a ClaimsPrincipal for the Blazor interface.
Register the provider in Program.cs:
using Microsoft.AspNetCore.Components.Authorization;
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<
AuthenticationStateProvider,
CustomAuthenticationStateProvider>();
The provider allows Blazor components to display the current authentication state.
Importantly, the ClaimsPrincipal created inside WebAssembly is only a representation of the user for the client interface. It does not authenticate API requests or replace backend authorization.
The backend remains responsible for validating the authentication cookie on every protected request.
Step 5: Display Authentication Information in Blazor
Blazor provides the AuthorizeView component to display content based on the authentication state.
For example:
<AuthorizeView>
<Authorized>
<h3>Welcome, @context.User.Identity?.Name</h3>
<p>You are successfully authenticated.</p>
</Authorized>
<NotAuthorized>
<p>Please sign in to continue.</p>
</NotAuthorized>
</AuthorizeView>
The component automatically displays the appropriate content based on the authentication state provider.
This makes it easier to build navigation menus, dashboards, and protected user interface sections.
However, hiding a button or page section does not protect the corresponding backend operation. The API must still enforce authorization independently.
Handling Logout and Session Expiration
Authentication is not complete without a proper logout process.
When a user logs out, the backend must invalidate the authentication session by removing the authentication cookie.
For cookie-based authentication, a logout endpoint can use the configured authentication scheme:
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(new
{
Message = "Logged out successfully."
});
}
After the backend clears the cookie, the Blazor application should refresh its authentication state.
For example, the custom provider can notify components that the user is now anonymous.
The application should also handle expired sessions. If an API request returns HTTP 401, the frontend can refresh the authentication state and redirect the user to the login page when appropriate.
Logout and other state-changing endpoints should be protected against cross-site request forgery.
Important Security Considerations for Production
Sharing authentication between Blazor WebAssembly and ASP.NET Core requires careful security configuration.
Use HTTPS Everywhere
Authentication cookies and other sensitive information should never be transmitted over unprotected HTTP connections.
Configure HTTPS for both the frontend and backend.
Protect Against CSRF Attacks
Cookie authentication automatically attaches eligible cookies to browser requests.
This creates a CSRF risk for state-changing operations.
Use antiforgery tokens for operations such as login, logout, updating user information, and deleting records. Validate these tokens on the backend.
Never Trust Client-Side Authorization
A user can inspect and modify client-side application code.
Therefore, authorization checks performed inside Blazor components are not sufficient.
Always use the Authorize attribute, authorization policies, or equivalent backend checks on protected endpoints.
Configure Cookie Properties Correctly
Use HttpOnly and Secure cookies, and choose an appropriate SameSite policy.
If the frontend and backend use different origins, review browser credential handling and cross-origin cookie restrictions carefully.
Handle Session Expiration
Applications should have a clear session expiration strategy.
Handle expired sessions gracefully and avoid leaving users with interfaces that appear authenticated while backend requests are being rejected.
Avoid Storing Sensitive Tokens in Browser Storage
Avoid storing access tokens, refresh tokens, or other sensitive credentials in localStorage or sessionStorage without carefully evaluating the security implications.
For browser-based applications, secure cookies or a properly designed backend-for-frontend architecture can reduce direct exposure of credentials to JavaScript.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Recommended Solution |
|---|
Blazor shows the user as anonymous | Authentication provider cannot retrieve user information | Verify the current-user API endpoint |
API returns HTTP 401 | Missing, expired, or invalid authentication cookie | Check cookie configuration and browser requests |
API returns HTTP 403 | User lacks the required permission | Review roles and authorization policies |
Login succeeds but API calls fail | Cookie is not included in subsequent requests | Verify origin, cookie properties, and credentials |
Authentication disappears after refresh | Client-only authentication state was not restored | Retrieve the session from the backend |
Logout does not update the interface | Authentication state was not refreshed | Notify the authentication state provider |
Cross-origin login fails | Incorrect CORS or cookie configuration | Configure explicit origins and credentials |
Browser developer tools are particularly useful when troubleshooting authentication issues.
Inspect the Network tab to verify whether the login response contains the expected Set-Cookie header and whether subsequent API requests include the authentication cookie.
Also inspect the browser console for CORS errors and review backend authentication logs.
Summary
Sharing authentication between Blazor WebAssembly and ASP.NET Core requires a clear separation between client-side authentication state and server-side security enforcement.
Cookie authentication is a practical choice when both applications share the same origin. It allows the browser to manage the authentication cookie while ASP.NET Core validates incoming requests.
Token-based authentication is another option when applications communicate with separate APIs or use external identity providers.
Blazor's AuthenticationStateProvider and AuthorizeView components make it easier to display authentication information in the user interface. However, these components should never replace backend authentication and authorization checks.
For production applications, developers should focus on HTTPS, secure cookie configuration, CSRF protection, session expiration, and proper API authorization.
With the right architecture, Blazor WebAssembly and ASP.NET Core can share a consistent authentication experience without creating separate and unnecessary authentication systems.
Arpit MishraPosted Nov 24, 2026, 9:35 AM
Clear walkthrough. One detail worth adding for the cookie route: if the Blazor app calls the API with fetch-based HttpClient, a 401 from an expired cookie can leave AuthorizeView showing the old user until something forces a refresh. A small DelegatingHandler that catches 401 responses and calls NotifyAuthenticationStateChanged with an anonymous principal keeps the UI in sync without waiting for a page reload.