Authentication and Authorization for Blazor Components

8 Jul 202612 minutes to read

This guide explains how to secure Blazor components using authentication and authorization. This enables you to control what users can see and interact with through UI-level security, while also protecting backend data access through data-level security.

Prerequisites

If you already have a Blazor project, proceed to the package installation section. Otherwise, create one using one of the following Blazor getting started guides.

Install required packages

Install required packages in your project using the NuGet Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage NuGet Packages for Solution), or the integrated terminal in Visual Studio Code (dotnet add package), or the .NET CLI.

Microsoft packages:

Syncfusion packages:

Add required namespaces

Open the ~/_Imports.razor file and add the required Blazor namespaces.

@using Microsoft.AspNetCore.Components.Authorization
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Schedule
@using Syncfusion.Blazor.Navigations

Add stylesheet and script resources

The theme stylesheet and script can be accessed from NuGet through Static Web Assets. Include the stylesheet and script references in the App.razor file.

<head>
    ...
    <!-- Blazor theme stylesheet -->
    <link href="_content/Syncfusion.Blazor.Themes/fluent2.css" rel="stylesheet" />
    ...
</head>
<body>
    ...
    <!-- Blazor core script (required for UI components) -->
    <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js"></script>
    ...
</body>

Configuring authentication and authorization

This guide uses authentication and authorization in a Blazor Server application with ASP.NET Core Identity. To set up ASP.NET Core Identity, refer to the following guide. This approach provides a standard and recommended way to manage user authentication, roles, and access control within a Blazor Server application, and can be further extended based on application requirements such as external login providers or advanced authorization scenarios.

Authentication with Blazor components

This section explains how to implement UI-level and data-level authorization in Blazor components such as Blazor DataGrid, Blazor Scheduler, and Blazor TreeView. UI-level authentication is demonstrated across all components using <AuthorizeView> to control the visibility of UI elements based on the user’s authentication state.

For data-level security, SfDataManager is configured to include Bearer tokens in API requests, enabling secure access to protected backend endpoints for components such as Blazor DataGrid and Blazor Scheduler. In this example, the Blazor TreeView component uses local data and focuses only on UI-level authentication.

Configure Bearer Token for API Requests

To securely access protected APIs, include a Bearer token in the request headers using SfDataManager.

Generating token

Create the token service file under the Services folder. In this example, use TokenService.cs as the file name.

public class TokenService
{
    // Replace this method with your actual token retrieval or generation logic
    public string GenerateToken()
    {
        // Replace this with your actual token generation logic.
        return Guid.NewGuid().ToString(); 
    }
}

Retrieve the token

Inject TokenService into your .razor component, then call TokenService.GenerateToken() inside a lifecycle method such as OnInitializedAsync, as shown in the component examples below.

@inject TokenService TokenService

@code {
    private string? token;

    protected override Task OnInitializedAsync()
    {
        token = TokenService.GenerateToken();
        return Task.CompletedTask;
    }
}

Blazor DataGrid component

The Blazor DataGrid can be secured by using the SfDataManager.Headers property, which enables the component to send authenticated requests to protected APIs. This ensures that the UI behavior (via <AuthorizeView>) is aligned with the underlying data access rules.

@using Syncfusion.Blazor.Grids
@using Syncfusion.Blazor.Data
@inject TokenService TokenService

<h3>DataGrid</h3>

<AuthorizeView>
    <Authorized Context="authContext">
        <SfGrid TValue="Order" AllowPaging="true">
            @* Replace with your actual protected API endpoint *@
            <SfDataManager Url="https://your-api.com/api/orders/" Adaptor="Adaptors.WebApiAdaptor" Headers="@HeaderData"></SfDataManager>
            <GridPageSettings PageSize="10"></GridPageSettings>
            <GridColumns>
                <GridColumn Field="@nameof(Order.OrderID)" HeaderText="Order ID" IsPrimaryKey="true" Width="120"></GridColumn>
                <GridColumn Field="@nameof(Order.CustomerID)" HeaderText="Customer Name" Width="150"></GridColumn>
                <GridColumn Field="@nameof(Order.OrderDate)" HeaderText="Order Date" Format="d" Type="ColumnType.Date" Width="130"></GridColumn>
                <GridColumn Field="@nameof(Order.Freight)" HeaderText="Freight" Format="C2" Width="120"></GridColumn>
            </GridColumns>
        </SfGrid>
        <p>Hello, @authContext.User.Identity?.Name!</p>
    </Authorized>
    <NotAuthorized>
        <p>Please log in to view the DataGrid.</p>
        <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

@code {
    private Dictionary<string, string> HeaderData { get; } = new Dictionary<string, string>();

    protected override Task OnInitializedAsync()
    {
        var token = TokenService.GenerateToken();
        HeaderData["Authorization"] = $"Bearer {token}";
        return Task.CompletedTask;
    }

    public class Order
    {
        public int? OrderID { get; set; }
        public string? CustomerID { get; set; }
        public DateTime? OrderDate { get; set; }
        public double? Freight { get; set; }
    }
}

Blazor Scheduler component

The Blazor Scheduler uses SfDataManager to send authenticated requests and retrieve event data securely from protected APIs. This ensures that only authorized users can access protected data from the API.

@using Syncfusion.Blazor.Schedule
@using Syncfusion.Blazor.Data
@inject TokenService TokenService

<AuthorizeView>
    <Authorized>
        <SfSchedule TValue="AppointmentData" Height="550px" SelectedDate="@currentDate">
            <ScheduleEventSettings TValue="AppointmentData">
                @* Replace with your actual protected API endpoint *@
                <SfDataManager Url="https://your-api.com/api/schedule" Headers="@HeaderData" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager>
            </ScheduleEventSettings>
            <ScheduleViews>
                <ScheduleView Option="View.Month"></ScheduleView>
            </ScheduleViews>
        </SfSchedule>
    </Authorized>
    <NotAuthorized>
        <p>Authentication required to view schedule.</p>
        <a href="Identity/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

@code {
    private DateTime currentDate = DateTime.Today;
    private Dictionary<string, string> HeaderData { get; } = new Dictionary<string, string>();

    protected override Task OnInitializedAsync()
    {
        var token = TokenService.GenerateToken();
        HeaderData["Authorization"] = $"Bearer {token}";
        return Task.CompletedTask;
    }

    public class AppointmentData
    {
        public int Id { get; set; }
        public string? Subject { get; set; }
        public string? Location { get; set; }
        public string? Description { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public bool? IsAllDay { get; set; }
        public string? CategoryColor { get; set; }
        public string? RecurrenceRule { get; set; }
    }
}

Blazor TreeView component

The following example demonstrates UI-level authorization using <AuthorizeView>. Blazor TreeView in this sample uses local data. For data-bound TreeView scenarios (e.g., async data loading from an API), apply the same SfDataManager + Bearer token pattern shown in the Blazor DataGrid component and Blazor Scheduler component sections.

@using Syncfusion.Blazor.Navigations

<AuthorizeView>
    <Authorized Context="authContext">
        <SfTreeView TValue="MailItem">
            <TreeViewFieldsSettings TValue="MailItem" Id="Id" DataSource="@MyFolder" Text="FolderName" ParentID="ParentId" HasChildren="HasSubFolders" Expanded="Expanded">
            </TreeViewFieldsSettings>
        </SfTreeView>
        <p>Welcome, @authContext.User.Identity?.Name!</p>
        <form method="post" action="Identity/Account/LogOut">
            <AntiforgeryToken />
            <button type="submit">Log out</button>
        </form>
    </Authorized>
    <NotAuthorized>
        <p>Log in to access the TreeView.</p>
        <a href="Identity/Account/Login">Log in</a>
        <a href="Identity/Account/Register">Register</a>
    </NotAuthorized>
</AuthorizeView>

@code {

    public class MailItem
    {
        public string? Id { get; set; }
        public string? ParentId { get; set; }
        public string? FolderName { get; set; }
        public bool Expanded { get; set; }
        public bool HasSubFolders { get; set; }
    }

   private List<MailItem> MyFolder = new List<MailItem>();

   protected override void OnInitialized()
   {
        // Load hierarchical folder data
        LoadFolderData();
   }

   private void LoadFolderData()
   {
        MyFolder.Add(new MailItem { Id = "1", FolderName = "Inbox", HasSubFolders = true, Expanded = true });
        MyFolder.Add(new MailItem { Id = "2", ParentId = "1", FolderName = "Categories", Expanded = true, HasSubFolders = true });
        MyFolder.Add(new MailItem { Id = "3", ParentId = "2", FolderName = "Primary" });
        MyFolder.Add(new MailItem { Id = "4", ParentId = "2", FolderName = "Social" });
        MyFolder.Add(new MailItem { Id = "5", ParentId = "2", FolderName = "Promotions" });
    }
}

Run the application

Press Ctrl+F5 (Windows) or ⌘+F5 (macOS) to launch the application.

Alternatively, run the application using the following .NET CLI command from the project root directory.

dotnet run

Expected behavior

  • Blazor components should render only for authorized users.
  • If the user is not authenticated, the application should display Register or Log in options instead of the Blazor components.
  • After a successful login, the user should be able to view the Blazor components such as Blazor DataGrid, Blazor Scheduler, and Blazor TreeView while navigating across different pages.

Output:
Blazor Authentication And Authorization

See also