--- title: ASP.NET Core Blazor authentication and authorization author: guardrex description: Learn about Blazor authentication and authorization scenarios. monikerRange: '>= aspnetcore-3.1' ms.author: riande ms.custom: mvc ms.date: 05/19/2020 no-loc: [Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR] uid: blazor/security/index --- # ASP.NET Core Blazor authentication and authorization ASP.NET Core supports the configuration and management of security in Blazor apps. Security scenarios differ between Blazor Server and Blazor WebAssembly apps. Because Blazor Server apps run on the server, authorization checks are able to determine: * The UI options presented to a user (for example, which menu entries are available to a user). * Access rules for areas of the app and components. Blazor WebAssembly apps run on the client. Authorization is *only* used to determine which UI options to show. Since client-side checks can be modified or bypassed by a user, a Blazor WebAssembly app can't enforce authorization access rules. [Razor Pages authorization conventions](xref:security/authorization/razor-pages-authorization) don't apply to routable Razor components. If a non-routable Razor component is [embedded in a page](xref:blazor/components/prerendering-and-integration), the page's authorization conventions indirectly affect the Razor component along with the rest of the page's content. > [!NOTE] > and aren't supported in Razor components. ## Authentication Blazor uses the existing ASP.NET Core authentication mechanisms to establish the user's identity. The exact mechanism depends on how the Blazor app is hosted, Blazor WebAssembly or Blazor Server. ### Blazor WebAssembly authentication In Blazor WebAssembly apps, authentication checks can be bypassed because all client-side code can be modified by users. The same is true for all client-side app technologies, including JavaScript SPA frameworks or native apps for any operating system. Add the following: * A package reference for [`Microsoft.AspNetCore.Components.Authorization`](https://www.nuget.org/packages/Microsoft.AspNetCore.Components.Authorization) to the app's project file. * The `Microsoft.AspNetCore.Components.Authorization` namespace to the app's `_Imports.razor` file. To handle authentication, use of a built-in or custom service is covered in the following sections. For more information on creating apps and configuration, see . ### Blazor Server authentication Blazor Server apps operate over a real-time connection that's created using SignalR. [Authentication in SignalR-based apps](xref:signalr/authn-and-authz) is handled when the connection is established. Authentication can be based on a cookie or some other bearer token. The built-in service for Blazor Server apps obtains authentication state data from ASP.NET Core's `HttpContext.User`. This is how authentication state integrates with existing ASP.NET Core authentication mechanisms. For more information on creating apps and configuration, see . ## AuthenticationStateProvider service is the underlying service used by the component and component to get the authentication state. You don't typically use directly. Use the [`AuthorizeView` component](#authorizeview-component) or [`Task`](#expose-the-authentication-state-as-a-cascading-parameter) approaches described later in this article. The main drawback to using directly is that the component isn't notified automatically if the underlying authentication state data changes. The service can provide the current user's data, as shown in the following example: ```razor @page "/" @using System.Security.Claims @using Microsoft.AspNetCore.Components.Authorization @inject AuthenticationStateProvider AuthenticationStateProvider

ClaimsPrincipal Data

@_authMessage

@if (_claims.Count() > 0) {
    @foreach (var claim in _claims) {
  • @claim.Type: @claim.Value
  • }
}

@_surnameMessage

@code { private string _authMessage; private string _surnameMessage; private IEnumerable _claims = Enumerable.Empty(); private async Task GetClaimsPrincipalData() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { _authMessage = $"{user.Identity.Name} is authenticated."; _claims = user.Claims; _surnameMessage = $"Surname: {user.FindFirst(c => c.Type == ClaimTypes.Surname)?.Value}"; } else { _authMessage = "The user is NOT authenticated."; } } } ``` If `user.Identity.IsAuthenticated` is `true` and because the user is a , claims can be enumerated and membership in roles evaluated. For more information on dependency injection (DI) and services, see and . ## Implement a custom AuthenticationStateProvider If the app requires a custom provider, implement and override `GetAuthenticationStateAsync`: ```csharp using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Authorization; public class CustomAuthStateProvider : AuthenticationStateProvider { public override Task GetAuthenticationStateAsync() { var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "mrfibuli"), }, "Fake authentication type"); var user = new ClaimsPrincipal(identity); return Task.FromResult(new AuthenticationState(user)); } } ``` In a Blazor WebAssembly app, the `CustomAuthStateProvider` service is registered in `Main` of `Program.cs`: ```csharp using Microsoft.AspNetCore.Components.Authorization; ... builder.Services.AddScoped(); ``` In a Blazor Server app, the `CustomAuthStateProvider` service is registered in `Startup.ConfigureServices`: ```csharp using Microsoft.AspNetCore.Components.Authorization; ... services.AddScoped(); ``` Using the `CustomAuthStateProvider` in the preceding example, all users are authenticated with the username `mrfibuli`. ## Expose the authentication state as a cascading parameter If authentication state data is required for procedural logic, such as when performing an action triggered by the user, obtain the authentication state data by defining a cascading parameter of type `Task<``>`: ```razor @page "/"

@_authMessage

@code { [CascadingParameter] private Task authenticationStateTask { get; set; } private string _authMessage; private async Task LogUsername() { var authState = await authenticationStateTask; var user = authState.User; if (user.Identity.IsAuthenticated) { _authMessage = $"{user.Identity.Name} is authenticated."; } else { _authMessage = "The user is NOT authenticated."; } } } ``` If `user.Identity.IsAuthenticated` is `true`, claims can be enumerated and membership in roles evaluated. Set up the `Task<``>` cascading parameter using the and components in the `App` component (`App.razor`): ```razor

Sorry, there's nothing at this address.

``` [!INCLUDE[](~/blazor/includes/prefer-exact-matches.md)] In a Blazor WebAssembly App, add services for options and authorization to `Program.Main`: ```csharp builder.Services.AddOptions(); builder.Services.AddAuthorizationCore(); ``` In a Blazor Server app, services for options and authorization are already present, so no further action is required. ## Authorization After a user is authenticated, *authorization* rules are applied to control what the user can do. Access is typically granted or denied based on whether: * A user is authenticated (signed in). * A user is in a *role*. * A user has a *claim*. * A *policy* is satisfied. Each of these concepts is the same as in an ASP.NET Core MVC or Razor Pages app. For more information on ASP.NET Core security, see the articles under [ASP.NET Core Security and Identity](xref:security/index). ## AuthorizeView component The component selectively displays UI content depending on whether the user is authorized. This approach is useful when you only need to *display* data for the user and don't need to use the user's identity in procedural logic. The component exposes a `context` variable of type , which you can use to access information about the signed-in user: ```razor

Hello, @context.User.Identity.Name!

You can only see this content if you're authenticated.

``` You can also supply different content for display if the user isn't authorized: ```razor

Hello, @context.User.Identity.Name!

You can only see this content if you're authorized.

Authentication Failure!

You're not signed in.

@code { private void SecureMethod() { ... } } ``` The content of `` and `` tags can include arbitrary items, such as other interactive components. A default event handler for an authorized element, such as the `SecureMethod` method for the ` Log in @code{ private async Task BeginLogout(MouseEventArgs args) { await SignOutManager.SetSignOutState(); Navigation.NavigateTo("authentication/logout"); } } ``` The following example is from the [Blazor Server project template](xref:blazor/project-structure) and uses ASP.NET Core Identity endpoints in the `Identity` area of the app to process Identity-related work. `Shared/LoginDisplay.razor`: ```razor Hello, @context.User.Identity.Name!
Register Log in
``` ### Role-based and policy-based authorization The component supports *role-based* or *policy-based* authorization. For role-based authorization, use the parameter: ```razor

You can only see this if you're an admin or superuser.

``` For more information, see . For policy-based authorization, use the parameter: ```razor

You can only see this if you satisfy the "content-editor" policy.

``` Claims-based authorization is a special case of policy-based authorization. For example, you can define a policy that requires users to have a certain claim. For more information, see . These APIs can be used in either Blazor Server or Blazor WebAssembly apps. If neither nor is specified, uses the default policy. ### Content displayed during asynchronous authentication Blazor allows for authentication state to be determined *asynchronously*. The primary scenario for this approach is in Blazor WebAssembly apps that make a request to an external endpoint for authentication. While authentication is in progress, displays no content by default. To display content while authentication occurs, use the `` tag: ```razor

Hello, @context.User.Identity.Name!

You can only see this content if you're authenticated.

Authentication in progress

You can only see this content while authentication is in progress.

``` This approach isn't normally applicable to Blazor Server apps. Blazor Server apps know the authentication state as soon as the state is established. content can be provided in a Blazor Server app's component, but the content is never displayed. ## [Authorize] attribute The [`[Authorize]` attribute](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) can be used in Razor components: ```razor @page "/" @attribute [Authorize] You can only see this if you're signed in. ``` > [!IMPORTANT] > Only use [`[Authorize]`](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) on `@page` components reached via the Blazor Router. Authorization is only performed as an aspect of routing and *not* for child components rendered within a page. To authorize the display of specific parts within a page, use instead. The [`[Authorize]` attribute](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) also supports role-based or policy-based authorization. For role-based authorization, use the parameter: ```razor @page "/" @attribute [Authorize(Roles = "admin, superuser")]

You can only see this if you're in the 'admin' or 'superuser' role.

``` For policy-based authorization, use the parameter: ```razor @page "/" @attribute [Authorize(Policy = "content-editor")]

You can only see this if you satisfy the 'content-editor' policy.

``` If neither nor is specified, [`[Authorize]`](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) uses the default policy, which by default is to treat: * Authenticated (signed-in) users as authorized. * Unauthenticated (signed-out) users as unauthorized. ## Customize unauthorized content with the Router component The component, in conjunction with the component, allows the app to specify custom content if: * The user fails an [`[Authorize]`](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) condition applied to the component. The markup of the [``](xref:Microsoft.AspNetCore.Components.Authorization.AuthorizeRouteView.NotAuthorized?displayProperty=nameWithType) element is displayed. The [`[Authorize]`](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) attribute is covered in the [`[Authorize]` attribute](#authorize-attribute) section. * Asynchronous authorization is in progress, which usually means that the process of authenticating the user is in progress. The markup of the [``](xref:Microsoft.AspNetCore.Components.Authorization.AuthorizeRouteView.Authorizing?displayProperty=nameWithType) element is displayed. * Content isn't found. The markup of the [``](xref:Microsoft.AspNetCore.Components.Routing.Router.NotFound?displayProperty=nameWithType) element is displayed. In the default [Blazor Server project template](xref:blazor/project-structure), the `App` component (`App.razor`) demonstrates how to set custom content: ```razor

Sorry

You're not authorized to reach this page.

You may need to log in as a different user.

Authorization in progress

Only visible while authorization is in progress.

Sorry

Sorry, there's nothing at this address.

``` [!INCLUDE[](~/blazor/includes/prefer-exact-matches.md)] The content of ``, ``, and `` tags can include arbitrary items, such as other interactive components. If the `` tag isn't specified, the uses the following fallback message: ```html Not authorized. ``` ## Notification about authentication state changes If the app determines that the underlying authentication state data has changed (for example, because the user signed out or another user has changed their roles), a [custom `AuthenticationStateProvider`](#implement-a-custom-authenticationstateprovider) can optionally invoke the method on the base class. This notifies consumers of the authentication state data (for example, ) to rerender using the new data. ## Procedural logic If the app is required to check authorization rules as part of procedural logic, use a cascaded parameter of type `Task<``>` to obtain the user's . `Task<``>` can be combined with other services, such as `IAuthorizationService`, to evaluate policies. ```razor @using Microsoft.AspNetCore.Authorization @inject IAuthorizationService AuthorizationService @code { [CascadingParameter] private Task authenticationStateTask { get; set; } private async Task DoSomething() { var user = (await authenticationStateTask).User; if (user.Identity.IsAuthenticated) { // Perform an action only available to authenticated (signed-in) users. } if (user.IsInRole("admin")) { // Perform an action only available to users in the 'admin' role. } if ((await AuthorizationService.AuthorizeAsync(user, "content-editor")) .Succeeded) { // Perform an action only available to users satisfying the // 'content-editor' policy. } } } ``` > [!NOTE] > In a Blazor WebAssembly app component, add the and namespaces: > > ```razor > @using Microsoft.AspNetCore.Authorization > @using Microsoft.AspNetCore.Components.Authorization > ``` > > These namespaces can be provided globally by adding them to the app's `_Imports.razor` file. ## Troubleshoot errors Common errors: * **Authorization requires a cascading parameter of type `Task\`. Consider using `CascadingAuthenticationState` to supply this.** * **`null` value is received for `authenticationStateTask`** It's likely that the project wasn't created using a Blazor Server template with authentication enabled. Wrap a `` around some part of the UI tree, for example in the `App` component (`App.razor`) as follows: ```razor ... ``` [!INCLUDE[](~/blazor/includes/prefer-exact-matches.md)] The supplies the `Task<``>` cascading parameter, which in turn it receives from the underlying DI service. ## Additional resources * [Microsoft identity platform documentation](/azure/active-directory/develop/) * * * [Build a custom version of the Authentication.MSAL JavaScript library](xref:blazor/security/webassembly/additional-scenarios#build-a-custom-version-of-the-authenticationmsal-javascript-library) * [Awesome Blazor: Authentication](https://github.com/AdrienTorris/awesome-blazor#authentication) community sample links