Course contentsShow
← C#
Lesson 1338 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Authentication and Authorization in Blazor

Secure application routes and components based on user claims and identity.

In this lesson, you will learn how to restrict access to specific parts of your Blazor application by verifying user identity and inspecting their security claims.

Understanding Identity and Authorization

Authentication tells us who the user is (e.g., "John Doe"), while authorization tells us what they are allowed to do (e.g., "John is an Administrator"). In Blazor, we handle this by integrating the AuthenticationStateProvider into our component lifecycle.

When a user navigates to a page, Blazor checks the AuthenticationState. If the user isn't logged in, or if they lack the required permissions, we can conditionally render content or force a redirect.

The AuthorizeView Component

The most common way to secure UI elements is the <AuthorizeView> component. It acts as a wrapper that automatically adapts its content based on whether the user is logged in or possesses specific roles or claims.

<AuthorizeView Roles="Admin">
    <Authorized>
        <button>Delete Database</button>
    </Authorized>
    <NotAuthorized>
        <p>You do not have permission to perform this action.</p>
    </NotAuthorized>
</AuthorizeView>

Securing Routes

To secure an entire page, you use the [Authorize] attribute at the top of your .razor file. When the router encounters this attribute, it consults the AuthenticationStateProvider. If the user isn't authenticated, the router automatically prevents access to the component and redirects the user to the login page.

@page "/admin-dashboard"
@attribute [Authorize(Roles = "Admin")]

<h1>Restricted Dashboard</h1>
<p>Only users with the 'Admin' role can see this.</p>

Behind the scenes, Blazor uses the AuthenticationState cascading value. Because it is a cascading value, you can access the user’s identity anywhere in your component tree by defining [CascadingParameter] private Task<AuthenticationState> AuthTask { get; set; }. This allows you to write custom logic in your C# code (like OnInitializedAsync) to inspect specific claims and decide whether to show data or trigger a navigation event.

Key Takeaway: Use the [Authorize] attribute to protect entire pages at the routing level, and use the <AuthorizeView> component to show or hide granular UI elements based on user roles and claims.