Live Chat Icon For mobile
Live Chat Icon

How do I add authentication to a Blazor WebAssembly app?

Platform: Blazor| Category : General, WebAssembly

Blazor authentication is implemented to determine who a particular user is. Blazor follows the existing ASP.NET Core authentication mechanisms to show a user’s identity.
Follow these steps to implement authentication within Blazor WebAssembly:

  1. Create a Blazor WebAssembly app with individual user account authentication in Visual Studio 2019.

  2. Install the NuGet package named “Microsoft.AspNetCore.Components.WebAssembly.Authentication” using the NuGet package manager.

  3. To support the authenticating service, add the AddOidcAuthentication service configuration to the Program.cs file.

    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    . . .

      builder.Services.AddOidcAuthentication(options =>
            builder.Configuration.Bind("Auth0", options.ProviderOptions);
            options.ProviderOptions.ResponseType = "code";

  4. In wwwroot/appsettings.json file, replace the Authority and Client ID placeholders with the proper values taken from the Auth0 dashboard.
    Note: Use Auth0; it will let you integrate authentication for configuring your application. Refer to this link for how to configure the application.

      "Auth0": {
        "Authority": "https://<YOUR_AUTH0_DOMAIN>",
        "ClientId": "<YOUR_CLIENT_ID>"

  5. Add the authentication service script reference to the index.html file, which handles the low-level details of the OIDC protocol.

        //. . .
        <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js">

  6. Add CascadingAuthenticationState and AuthorizeRouteView to display the page matching the specified route only if the user is authorized. Otherwise, it redirects to the Login page.

    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <p>You're not authorized to reach this page. You need to log in.</p>
            <p>Sorry, there's nothing at this address.</p>        

  7. Create a Razor component to allow the user to log in to be authenticated in the Shared folder.

    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @inject NavigationManager UriHelper
    @inject SignOutSessionStateManager SignOutManager
            Hello, @context.User.Identity.Name!
            <a href="#" @onclick="OnClickEvent">Log out</a>
            <a href="authentication/login">Log in</a>
        private async Task OnClickEvent(MouseEventArgs args)
            await SignOutManager.SetSignOutState();

  8. Reference the LoginControl page in the MainLayout.razor page.

    <div class="main">
            <div class="top-row px-4 auth">
                <LoginControl />
                <a href="" target="_blank">About</a>
            <div class="content px-4">

  9. Create an Authentication.razor component in the Pages folder to authenticate the user when logging in and out of the app.

    @page "/authentication/{action}"
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @using Microsoft.Extensions.Configuration
    @inject NavigationManager UriHelper
    @inject IConfiguration Config
    <RemoteAuthenticatorView Action="@Action">
                var authority = (string)Config["Auth0:Authority"];
                var clientId = (string)Config["Auth0:ClientId"];
        public string Action { get; set; }

  10. Now display the authorized content when the app is authorized. If the app is not authorized, display the “Not Authorized” message to the user.

    @page "/"
            <h1>Hello, @context.User.Identity.Name !</h1>
            <p>Welcome to your new app.</p>
            <p>Not Authorized</p>

  11. Press Ctrl + F5 to run the application and click Log in in the header to authenticate the user.

Refer to this documentation for more details.

View Sample in GitHub 

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.