Authentication and Authorization in Blazor
Authentication and Authorization in Blazor
Blazor provides a seamless way to handle authentication and authorization, especially when using a Blazor WebAssembly Hosted application. This blog post will guide you through the process of adding secure user management to your app using ASP.NET Core Identity and Blazor's built-in components.
๐ฏ Learning Objectives
By the end of this guide, you will be able to:
- Add authentication to a new Blazor WebAssembly Hosted app.
- Understand the role of key authentication components like `AuthenticationStateProvider`.
- Protect API endpoints from unauthorized access.
- Secure Razor pages and components using the `[Authorize]` attribute and the `<AuthorizeView>` component.
✅ Step-by-Step Demo: Add Authentication to a Blazor WebAssembly Hosted App
๐ ️ Step 1: Create a New Hosted Blazor WebAssembly Project With Authentication
The easiest way to get started is by creating a new project with authentication enabled from the start. We'll use the command line for this.
dotnet new blazorwasm -ho -au Individual -o SecureCommentDemo
**Important:** This is a command to be executed in your terminal or Command Prompt. It is not part of the application code itself and will cause a syntax error if run in a code editor or browser console.
This command creates a complete solution with user registration, login, and a secure API already configured.
๐ Understanding the Project Structure with Auth Enabled
- `SecureCommentDemo.Client/`: This is the Blazor WebAssembly frontend. It contains Razor pages for login, registration, and components for managing authentication state.
- `SecureCommentDemo.Server/`: This is the ASP.NET Core backend. It hosts the Blazor app and contains the Web API controllers and the ASP.NET Core Identity database setup.
- `SecureCommentDemo.Shared/`: This project holds models and other shared code that both the client and server projects can reference.
๐ Step 2: Understand Authentication Flow
Blazor's authentication system relies on several key components:
| Component | Purpose |
|---|---|
| **`AuthenticationStateProvider`** | A core service that provides the current user's authentication state to the rest of the app. |
| **`[Authorize]`** | An attribute used to restrict access to pages, components, or API endpoints. |
| **`<AuthorizeView>`** | A component for conditional UI rendering based on the user's login status. |
| **`RemoteAuthenticatorView`** | A built-in component that handles the UI for all the login, logout, and registration logic. |
๐ Step 3: Secure a Page using `[Authorize]`
Let's modify the default `FetchData.razor` page to require authentication.
In `Client/Pages/FetchData.razor`, add the `[Authorize]` attribute at the top of the file. We'll also use `
@page "/fetchdata"
@using SecureCommentDemo.Shared
@inject HttpClient Http
@attribute [Authorize]
<h3>Weather forecast</h3>
<AuthorizeView>
<Authorized>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
</Authorized>
<NotAuthorized>
<p>You must be logged in to view weather data.</p>
</NotAuthorized>
</AuthorizeView>
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
}
๐ Step 4: Secure the API on the Server
The frontend security is important, but a true security implementation requires protecting the backend API as well. We will use the `[Authorize]` attribute on the `WeatherForecastController` to ensure only authenticated users can access the data.
In `Server/Controllers/WeatherForecastController.cs`, add `using Microsoft.AspNetCore.Authorization;` and then add the `[Authorize]` attribute to the controller class.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SecureCommentDemo.Shared;
namespace SecureCommentDemo.Server.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize] // <-- This is the key change
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
๐งช Try the Auth Flow
Now, when you run the application and try to access `/fetchdata` without logging in, Blazor will handle the unauthorized request and redirect you to the login page. Once you log in, you will be able to see the weather data, proving that both the UI and the underlying API are secure.
๐ Summary
This guide showed you how to easily integrate authentication and authorization into a Blazor WebAssembly Hosted app using the built-in ASP.NET Core features. This layered approach ensures that both your front-end UI and back-end APIs are protected from unauthorized access.
| Concept | Implementation |
|---|---|
| **Authentication** | ASP.NET Core Identity provides the backend for user management. |
| **Authorization** | `[Authorize]` and `<AuthorizeView>` are used to control access. |
| **UI Integration** | The `RemoteAuthenticatorView` handles the login/register/logout user interface. |
| **Page Protection** | Adding `[Authorize]` to a `.razor` file restricts access to the entire page. |
| **API Protection** | Adding `[Authorize]` to an API controller secures the data it serves. |
Comments
Post a Comment