Blazor Navigation and Auth

Back

Loading concept...

🚀 Blazor Navigation & Authentication

The Story: Your App is a Building

Imagine your Blazor app is a fancy building with many rooms. Some rooms are open to everyone (like the lobby). Other rooms need a special key card to enter (like the VIP lounge).

Today, we’ll learn:

  • How to move between rooms (Blazor Routing)
  • How to use the elevator panel (NavigationManager)
  • How to check key cards at doors (Authentication)
  • How to show/hide things based on access (AuthorizeView)
  • How to share key card info everywhere (CascadingAuthenticationState)

🗺️ Blazor Routing: The Building’s Map

What Is It?

Routing is like a map of your building. When someone types a room number (URL), the map tells them exactly which room to show.

Simple Example

@page "/home"

<h1>Welcome Home!</h1>

What’s happening?

  • @page "/home" = “This room is at address /home”
  • When someone visits /home, this page appears!

Multiple Routes for One Page

@page "/about"
@page "/about-us"

<h1>About Our Company</h1>

One room, two door numbers! Both /about and /about-us lead here.

Routes with Parameters

Sometimes you need to pass information through the door.

@page "/user/{Id}"

<h1>User Profile: @Id</h1>

@code {
    [Parameter]
    public string Id { get; set; }
}

Real example: /user/123 shows “User Profile: 123”

Route Constraints

Want only numbers? Add a rule!

@page "/product/{Id:int}"

@code {
    [Parameter]
    public int Id { get; set; }
}

Now /product/abc won’t work - only /product/42 does!

graph TD A["User types URL"] --> B{Route exists?} B -->|Yes| C["Show matching page"] B -->|No| D["Show 404 error"] C --> E["Page renders"]

🎮 NavigationManager: The Elevator Panel

What Is It?

NavigationManager is like the elevator control panel. It helps you:

  • Move to different floors (pages)
  • Know which floor you’re on (current URL)

Inject It First

@inject NavigationManager NavManager

Think of this as: “Hey building, give me access to the elevator!”

Navigate to a Page

<button @onclick="GoHome">
    Take me home!
</button>

@code {
    void GoHome()
    {
        NavManager.NavigateTo("/home");
    }
}

Click the button → Whoosh → You’re at /home!

Get Current Location

<p>You are here: @NavManager.Uri</p>

Shows the full address where you currently are.

Force Page Reload

NavManager.NavigateTo("/login", forceLoad: true);

Like pressing the emergency reset - reloads everything fresh!

Listen for Navigation Changes

@code {
    protected override void OnInitialized()
    {
        NavManager.LocationChanged += HandleLocationChanged;
    }

    void HandleLocationChanged(object sender,
        LocationChangedEventArgs e)
    {
        Console.WriteLine(quot;Moved to: {e.Location}");
    }
}

Now you know whenever someone uses the elevator!


🔐 Blazor Authentication: The Key Card System

What Is It?

Authentication answers one question: “Who are you?”

It’s like the security desk asking for your ID before letting you in.

The Authentication Basics

graph TD A["User arrives"] --> B{Has key card?} B -->|No| C["Guest - limited access"] B -->|Yes| D["Check the card"] D --> E{Card valid?} E -->|Yes| F["Welcome! Full access"] E -->|No| G["Access denied"]

Setting Up Authentication

In your Program.cs:

builder.Services
    .AddAuthorizationCore();

This turns ON the key card system!

The AuthenticationState

This is your key card information:

public class AuthenticationState
{
    public ClaimsPrincipal User { get; }
}

User = All info about the person (name, role, etc.)

Check If User Is Logged In

@code {
    [CascadingParameter]
    Task<AuthenticationState> AuthState { get; set; }

    async Task CheckUser()
    {
        var state = await AuthState;
        bool loggedIn = state.User.Identity.IsAuthenticated;

        if (loggedIn)
        {
            string name = state.User.Identity.Name;
            Console.WriteLine(quot;Hello, {name}!");
        }
    }
}

👁️ AuthorizeView: The Magic Door Signs

What Is It?

AuthorizeView is like smart signs on doors that change based on who’s looking.

  • Guest sees: “Please log in”
  • Member sees: “Welcome back!”
  • Admin sees: “Welcome back! Here are admin controls”

Basic Usage

<AuthorizeView>
    <Authorized>
        <p>Hello, @context.User.Identity.Name!</p>
        <button>Log Out</button>
    </Authorized>
    <NotAuthorized>
        <p>Please log in to continue.</p>
        <button>Log In</button>
    </NotAuthorized>
</AuthorizeView>

Magic! The right content shows automatically.

Show Content for Specific Roles

<AuthorizeView Roles="Admin">
    <Authorized>
        <button>Delete Everything</button>
    </Authorized>
</AuthorizeView>

Only Admins see the dangerous button!

Multiple Roles

<AuthorizeView Roles="Admin, Manager">
    <p>You can manage the team.</p>
</AuthorizeView>

Admins OR Managers can see this.

Policy-Based Authorization

<AuthorizeView Policy="AtLeast21">
    <p>Here's the adult content.</p>
</AuthorizeView>

Custom rules! Maybe checking age, subscription, etc.

Loading State

<AuthorizeView>
    <Authorizing>
        <p>Checking your access...</p>
    </Authorizing>
    <Authorized>
        <p>You're in!</p>
    </Authorized>
</AuthorizeView>

Shows a loading message while checking credentials.

graph TD A["AuthorizeView"] --> B{Checking...} B --> C{Authorized?} C -->|Yes| D["Show Authorized content"] C -->|No| E["Show NotAuthorized content"] C -->|Loading| F["Show Authorizing content"]

🌊 CascadingAuthenticationState: Sharing Keys Everywhere

What Is It?

Imagine having to show your ID at every single door in the building. Exhausting!

CascadingAuthenticationState is like wearing a visible badge. Every room can see it automatically.

Setting It Up

Wrap your app in App.razor:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView
                RouteData="@routeData"
                DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <p>Sorry, you can't access this.</p>
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <p>Page not found!</p>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

What This Does

  1. CascadingAuthenticationState = Makes auth info available everywhere
  2. AuthorizeRouteView = Checks permissions before showing pages
  3. Every component can now access AuthenticationState!

Access Auth State in Any Component

@code {
    [CascadingParameter]
    private Task<AuthenticationState> AuthStateTask { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            // User is logged in!
        }
    }
}

No need to inject anything special - it just flows down to every component!

Protect Entire Pages

@page "/secret"
@attribute [Authorize]

<h1>Secret Page</h1>
<p>Only logged-in users see this!</p>

The [Authorize] attribute = “Key card required!”

Protect with Roles

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

<h1>Admin Panel</h1>

Only Admins can enter this room!


🎯 Putting It All Together

Here’s how everything connects:

graph TD A["CascadingAuthenticationState"] --> B["Wraps entire app"] B --> C["AuthorizeRouteView"] C --> D{User authenticated?} D -->|Yes| E["Show protected page"] D -->|No| F["Show login/error"] E --> G["Components use AuthorizeView"] G --> H["Show/hide based on roles"] E --> I["NavigationManager"] I --> J["Move between pages"]

Complete Example: A Protected Dashboard

@page "/dashboard"
@attribute [Authorize]
@inject NavigationManager NavManager

<AuthorizeView>
    <Authorized>
        <h1>Welcome, @context.User.Identity.Name!</h1>

        <AuthorizeView Roles="Admin">
            <Authorized>
                <button @onclick="GoToAdmin">
                    Admin Panel
                </button>
            </Authorized>
        </AuthorizeView>

        <button @onclick="GoHome">
            Back to Home
        </button>
    </Authorized>
</AuthorizeView>

@code {
    void GoToAdmin() => NavManager.NavigateTo("/admin");
    void GoHome() => NavManager.NavigateTo("/home");
}

🧠 Quick Recap

Concept What It Does Analogy
Routing Maps URLs to pages Building map
NavigationManager Moves between pages Elevator panel
Authentication Checks who you are Security desk
AuthorizeView Shows/hides content Smart door signs
CascadingAuthState Shares auth everywhere Visible badge

🚀 You Did It!

You now understand how Blazor apps:

  • Navigate between pages smoothly
  • Protect pages from unauthorized access
  • Show different content based on who’s logged in
  • Share authentication info across the entire app

Think of it as building a secure, smart building where every room knows exactly who should see what. And you’re the architect! 🏗️

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.