RO EN

Introduction to Authentication in Blazor WebAssembly

Introduction to Authentication in Blazor WebAssembly
Doru Bulubasa
06 June 2025
12 views

Authentication is essential in modern applications. In Blazor WebAssembly, we can simulate a login/logout system using a custom AuthenticationStateProvider.



🔧 1. Implementing a CustomAuthenticationStateProvider

public class CustomAuthStateProvider : AuthenticationStateProvider
{
    private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());

    private ClaimsPrincipal _user;

    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        if (_user == null)
            return Task.FromResult(new AuthenticationState(_anonymous));

        return Task.FromResult(new AuthenticationState(_user));
    }

    public void Login(string username)
    {
        var identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, username),
        }, "MockAuthentication");

        _user = new ClaimsPrincipal(identity);
        NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
    }

    public void Logout()
    {
        _user = null;
        NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
    }
}


🔧 2. Registration in Program.cs

builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();


🧑‍💼 3. Login Page (Pages/Login.razor)

@inject CustomAuthStateProvider AuthProvider
@inject NavigationManager Nav

<h3>Login</h3>

<input @bind="username" placeholder="Username" />
<button @onclick="PerformLogin">Login</button>

@code {
    private string username;

    private void PerformLogin()
    {
        AuthProvider.Login(username);
        Nav.NavigateTo("/");
    }
}


🔓 4. Logout (for example, in a menu)

@inject CustomAuthStateProvider AuthProvider
<button @onclick="() => AuthProvider.Logout()">Logout</button>


🔐 5. Protected Page (Pages/Secure.razor)

@attribute [Authorize]
<h3>Protected Information</h3>
<p>Only logged-in users can see this page.</p>


🔁 6. Add App.razor with CascadingAuthenticationState

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <p>Page not found.</p>
        </NotFound>
    </Router>
</CascadingAuthenticationState>


✅ 7. Redirect to login if the user is not authenticated

@using Microsoft.AspNetCore.Components.Authorization
@inject NavigationManager Nav
@attribute [Authorize]

<AuthorizeView>
    <Authorized>
        @ChildContent
    </Authorized>
    <NotAuthorized>
        @code {
            protected override void OnInitialized()
            {
                Nav.NavigateTo("/login");
            }
        }
    </NotAuthorized>
</AuthorizeView>

📝 Summary

In this article, you learned how to:

  • Create a custom AuthenticationStateProvider

  • Simulate login/logout in Blazor WebAssembly

  • Protect pages with [Authorize]

  • Redirect unauthenticated users