I-edit

Ibahagi sa


Secure ASP.NET Core server-side Blazor apps

Note

This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.

Warning

This version of ASP.NET Core is no longer supported. For more information, see .NET and .NET Core Support Policy. For the current release, see the .NET 8 version of this article.

Important

This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 9 version of this article.

This article explains how to secure server-side Blazor apps as ASP.NET Core applications.

Server-side Blazor apps are configured for security in the same manner as ASP.NET Core apps. For more information, see the articles under ASP.NET Core security topics.

The authentication context is only established when the app starts, which is when the app first connects to the WebSocket. The authentication context is maintained for the lifetime of the circuit. Apps periodically revalidate the user's authentication state every 30 minutes.

If the app must capture users for custom services or react to updates to the user, see Server-side ASP.NET Core Blazor additional security scenarios.

Blazor differs from a traditional server-rendered web apps that make new HTTP requests with cookies on every page navigation. Authentication is checked during navigation events. However, cookies aren't involved. Cookies are only sent when making an HTTP request to a server, which isn't what happens when the user navigates in a Blazor app. During navigation, the user's authentication state is checked within the Blazor circuit, which you can update at any time on the server using a revalidating AuthenticationStateProvider](#additional-authentication-state-providers).

Important

Implementing a custom NavigationManager to achieve authentication validation during navigation isn't recommended. If the app must execute custom authentication state logic during navigation, use a custom AuthenticationStateProvider.

Note

The code examples in this article adopt nullable reference types (NRTs) and .NET compiler null-state static analysis, which are supported in ASP.NET Core in .NET 6 or later. When targeting ASP.NET Core 5.0 or earlier, remove the null type designation (?) from the examples in this article.

Server-side security of sensitive data and credentials

In test/staging and production environments, server-side Blazor code and web APIs should use secure authentication flows that avoid maintaining credentials within project code or configuration files. Outside of local development testing, we recommend avoiding the use of environment variables to store sensitive data, as environment variables aren't the most secure approach. For local development testing, the Secret Manager tool is recommended for securing sensitive data. For more information, see the following resources:

For client-side and server-side local development and testing, use the Secret Manager tool to secure sensitive credentials.

Project template

Create a new server-side Blazor app by following the guidance in Tooling for ASP.NET Core Blazor.

After choosing the server-side app template and configuring the project, select the app's authentication under Authentication type:

  • None (default): No authentication.
  • Individual Accounts: User accounts are stored within the app using ASP.NET Core Identity.

Blazor Identity UI (Individual Accounts)

Blazor supports generating a full Blazor-based Identity UI when you choose the authentication option for Individual Accounts.

The Blazor Web App template scaffolds Identity code for a SQL Server database. The command line version uses SQLite and includes a SQLite database for Identity.

The template:

  • Supports interactive server-side rendering (interactive SSR) and client-side rendering (CSR) scenarios with authenticated users.
  • Adds Identity Razor components and related logic for routine authentication tasks, such as signing users in and out. The Identity components also support advanced Identity features, such as account confirmation and password recovery and multifactor authentication using a third-party app. Note that the Identity components themselves don't support interactivity.
  • Adds the Identity-related packages and dependencies.
  • References the Identity packages in _Imports.razor.
  • Creates a custom user Identity class (ApplicationUser).
  • Creates and registers an EF Core database context (ApplicationDbContext).
  • Configures routing for the built-in Identity endpoints.
  • Includes Identity validation and business logic.

To inspect the Blazor framework's Identity components, access them in the Pages and Shared folders of the Account folder in the Blazor Web App project template (reference source).

When you choose the Interactive WebAssembly or Interactive Auto render modes, the server handles all authentication and authorization requests, and the Identity components render statically on the server in the Blazor Web App's main project.

The framework provides a custom AuthenticationStateProvider in both the server and client (.Client) projects to flow the user's authentication state to the browser. The server project calls AddAuthenticationStateSerialization, while the client project calls AddAuthenticationStateDeserialization. Authenticating on the server rather than the client allows the app to access authentication state during prerendering and before the .NET WebAssembly runtime is initialized. The custom AuthenticationStateProvider implementations use the Persistent Component State service (PersistentComponentState) to serialize the authentication state into HTML comments and then read it back from WebAssembly to create a new AuthenticationState instance. For more information, see the Manage authentication state in Blazor Web Apps section.

Only for Interactive Server solutions, IdentityRevalidatingAuthenticationStateProvider (reference source) is a server-side AuthenticationStateProvider that revalidates the security stamp for the connected user every 30 minutes an interactive circuit is connected.

When you choose the Interactive WebAssembly or Interactive Auto render modes, the server handles all authentication and authorization requests, and the Identity components render statically on the server in the Blazor Web App's main project. The project template includes a PersistentAuthenticationStateProvider class (reference source) in the .Client project to synchronize the user's authentication state between the server and the browser. The class is a custom implementation of AuthenticationStateProvider. The provider uses the Persistent Component State service (PersistentComponentState) to prerender the authentication state and persist it to the page.

In the main project of a Blazor Web App, the authentication state provider is named either IdentityRevalidatingAuthenticationStateProvider (reference source) (Server interactivity solutions only) or PersistingRevalidatingAuthenticationStateProvider (reference source) (WebAssembly or Auto interactivity solutions).

Blazor Identity depends on DbContext instances not created by a factory, which is intentional because DbContext is sufficient for the project template's Identity components to render statically without supporting interactivity.

For a description on how global interactive render modes are applied to non-Identity components while at the same time enforcing static SSR for the Identity components, see ASP.NET Core Blazor render modes.

For more information on persisting prerendered state, see Prerender ASP.NET Core Razor components.

Note

Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Manage authentication state in Blazor Web Apps

This section applies to Blazor Web Apps that adopt:

  • Individual Accounts
  • Client-side rendering (CSR, WebAssembly-based interactivity).

A client-side authentication state provider is only used within Blazor and isn't integrated with the ASP.NET Core authentication system. During prerendering, Blazor respects the metadata defined on the page and uses the ASP.NET Core authentication system to determine if the user is authenticated. When a user navigates from one page to another, a client-side authentication provider is used. When the user refreshes the page (full-page reload), the client-side authentication state provider isn't involved in the authentication decision on the server. Since the user's state isn't persisted by the server, any authentication state maintained client-side is lost.

To address this, the best approach is to perform authentication within the ASP.NET Core authentication system. The client-side authentication state provider only takes care of reflecting the user's authentication state. Examples for how to accomplish this with authentication state providers are demonstrated by the Blazor Web App project template and described below.

In the server project's Program file, call AddAuthenticationStateSerialization, which serializes the AuthenticationState returned by the server-side AuthenticationStateProvider using the Persistent Component State service (PersistentComponentState):

builder.Services.AddRazorComponents()
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization();

The API only serializes the server-side name and role claims for access in the browser. To include all claims, set SerializeAllClaims to true in the server-side call to AddAuthenticationStateSerialization:

builder.Services.AddRazorComponents()
    .AddInteractiveWebAssemblyComponents()
    .AddAuthenticationStateSerialization(
        options => options.SerializeAllClaims = true);

In the client (.Client) project's Program file, call AddAuthenticationStateDeserialization, which adds an AuthenticationStateProvider where the AuthenticationState is deserialized from the server using AuthenticationStateData and the Persistent Component State service (PersistentComponentState). There should be a corresponding call to AddAuthenticationStateSerialization in the server project.

builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddAuthenticationStateDeserialization();

Note

Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Scaffold Identity

For more information on scaffolding Identity into a server-side Blazor app, see Scaffold Identity in ASP.NET Core projects.

Scaffold Identity into a server-side Blazor app:

Additional claims and tokens from external providers

To store additional claims from external providers, see Persist additional claims and tokens from external providers in ASP.NET Core.

Azure App Service on Linux with Identity Server

Specify the issuer explicitly when deploying to Azure App Service on Linux with Identity Server. For more information, see Use Identity to secure a Web API backend for SPAs.

Inject AuthenticationStateProvider for services scoped to a component

Don't attempt to resolve AuthenticationStateProvider within a custom scope because it results in the creation of a new instance of the AuthenticationStateProvider that isn't correctly initialized.

To access the AuthenticationStateProvider within a service scoped to a component, inject the AuthenticationStateProvider with the @inject directive or the [Inject] attribute and pass it to the service as a parameter. This approach ensures that the correct, initialized instance of the AuthenticationStateProvider is used for each user app instance.

ExampleService.cs:

public class ExampleService
{
    public async Task<string> ExampleMethod(AuthenticationStateProvider authStateProvider)
    {
        var authState = await authStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity is not null && user.Identity.IsAuthenticated)
        {
            return $"{user.Identity.Name} is authenticated.";
        }
        else
        {
            return "The user is NOT authenticated.";
        }
    }
}

Register the service as scoped. In a server-side Blazor app, scoped services have a lifetime equal to the duration of the client connection circuit.

In the Program file:

builder.Services.AddScoped<ExampleService>();

In Startup.ConfigureServices of Startup.cs:

services.AddScoped<ExampleService>();

In the following InjectAuthStateProvider component:

InjectAuthStateProvider.razor:

@page "/inject-auth-state-provider"
@inherits OwningComponentBase
@inject AuthenticationStateProvider AuthenticationStateProvider

<h1>Inject <code>AuthenticationStateProvider</code> Example</h1>

<p>@message</p>

@code {
    private string? message;
    private ExampleService? ExampleService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ExampleService = ScopedServices.GetRequiredService<ExampleService>();

        message = await ExampleService.ExampleMethod(AuthenticationStateProvider);
    }
}
@page "/inject-auth-state-provider"
@inject AuthenticationStateProvider AuthenticationStateProvider
@inherits OwningComponentBase

<h1>Inject <code>AuthenticationStateProvider</code> Example</h1>

<p>@message</p>

@code {
    private string? message;
    private ExampleService? ExampleService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ExampleService = ScopedServices.GetRequiredService<ExampleService>();

        message = await ExampleService.ExampleMethod(AuthenticationStateProvider);
    }
}

For more information, see the guidance on OwningComponentBase in ASP.NET Core Blazor dependency injection.

Unauthorized content display while prerendering with a custom AuthenticationStateProvider

To avoid showing unauthorized content, for example content in an AuthorizeView component, while prerendering with a custom AuthenticationStateProvider, adopt one of the following approaches:

  • Disable prerendering: Indicate the render mode with the prerender parameter set to false at the highest-level component in the app's component hierarchy that isn't a root component.

    Note

    Making a root component interactive, such as the App component, isn't supported. Therefore, prerendering can't be disabled directly by the App component.

    For apps based on the Blazor Web App project template, prerendering is typically disabled where the Routes component is used in the App component (Components/App.razor) :

    <Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    

    Also, disable prerendering for the HeadOutlet component:

    <HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
    

    You can also selectively control the render mode applied to the Routes component instance. For example, see ASP.NET Core Blazor render modes.

  • Disable prerendering: Open the _Host.cshtml file and change the render-mode attribute of the Component Tag Helper to Server:

    <component type="typeof(App)" render-mode="Server" />
    
  • Authenticate the user on the server before the app starts: To adopt this approach, the app must respond to a user's initial request with the Identity-based sign-in page or view and prevent any requests to Blazor endpoints until they're authenticated. For more information, see Create an ASP.NET Core app with user data protected by authorization. After authentication, unauthorized content in prerendered Razor components is only shown when the user is truly unauthorized to view the content.

User state management

In spite of the word "state" in the name, AuthenticationStateProvider isn't for storing general user state. AuthenticationStateProvider only indicates the user's authentication state to the app, whether they are signed into the app and who they are signed in as.

Authentication uses the same ASP.NET Core Identity authentication as Razor Pages and MVC apps. The user state stored for ASP.NET Core Identity flows to Blazor without adding additional code to the app. Follow the guidance in the ASP.NET Core Identity articles and tutorials for the Identity features to take effect in the Blazor parts of the app.

For guidance on general state management outside of ASP.NET Core Identity, see ASP.NET Core Blazor state management.

Additional authentication state providers

Two additional classes derived from AuthenticationStateProvider help with managing authentication state on the server:

Note

Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Authentication state management at sign out

Server-side Blazor persists user authentication state for the lifetime of the circuit, including across browser tabs. To proactively sign off a user across browser tabs when the user signs out on one tab, you must implement a RevalidatingServerAuthenticationStateProvider (reference source) with a short RevalidationInterval.

Note

Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Temporary redirection URL validity duration

This section applies to Blazor Web Apps.

Use the RazorComponentsServiceOptions.TemporaryRedirectionUrlValidityDuration option to get or set the lifetime of ASP.NET Core Data Protection validity for temporary redirection URLs emitted by Blazor server-side rendering. These are only used transiently, so the lifetime only needs to be long enough for a client to receive the URL and begin navigation to it. However, it should also be long enough to allow for clock skew across servers. The default value is five minutes.

In the following example the value is extended to seven minutes:

builder.Services.AddRazorComponents(options => 
    options.TemporaryRedirectionUrlValidityDuration = 
        TimeSpan.FromMinutes(7));

Additional resources