IC Improve Code Recipes

Recipe 16.5 · Python

Navigation Menus from Configuration

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

The menu is either a Web.sitemap file with role trimming that nobody fully understands, or a master page code-behind full of if (User.IsInRole(...)) menu.Items.Add(...). Adding a page means editing code, and the menu shows links the user isn't allowed to open.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

XML
<!-- Not to copy: Web.sitemap plus roles that drift from code -->
<siteMap>
  <siteMapNode url="~/Default.aspx" title="Home">
    <siteMapNode url="~/Billing/Invoices.aspx" title="Invoices"
                 roles="Finance,Admin" />
    <siteMapNode url="~/Admin/Users.aspx" title="Users"
                 roles="Admin" />
  </siteMapNode>
</siteMap>

The roles attribute only hides links when security trimming is switched on, and it is a second, separate list from the rules that actually protect the pages. The two drift apart.

The improved recipe

Configuration in appsettings.json:

JSON
{
  "Navigation": {
    "Items": [
      { "Title": "Home", "Url": "/" },
      {
        "Title": "Billing",
        "Policy": "Finance",
        "Children": [
          { "Title": "Invoices", "Url": "/invoices" },
          { "Title": "Payments", "Url": "/payments" }
        ]
      },
      { "Title": "Users", "Url": "/admin/users", "Policy": "Admin" }
    ]
  }
}

The options, the view component and the registration:

The view for the component:

Text
@* Views/Shared/Components/MainMenu/Default.cshtml *@
@using ImproveCode.Web.Navigation
@model IReadOnlyList<MenuEntry>

<ul class="nav">
@foreach (MenuEntry item in Model)
{
    <li class="nav-item @(item.IsActive ? "active" : "")">
        <a class="nav-link" href="@item.Url">@item.Title</a>
        @if (item.Children.Count > 0)
        {
            <ul class="sub-nav">
            @foreach (MenuEntry child in item.Children)
            {
                <li class="@(child.IsActive ? "active" : "")">
                    <a href="@child.Url">@child.Title</a>
                </li>
            }
            </ul>
        }
    </li>
}
</ul>

In the layout: @await Component.InvokeAsync("MainMenu").

Requirements: Python 3.12+. Install: pip install pydantic

Python Navigation menu built from configuration, filtered by policy, with active state (p369_r16_5_config_driven_navigation_menu.py)
"""Navigation menu built from configuration, filtered by policy, with active state

Source: ImproveCode, Chapter 16, Recipe 16.5 "Navigation Menus from Configuration"
Section: The improved recipe
Book page: 369-371  -- original C# listing
Converted from C# to Python.
Options binding/validation becomes pydantic models validated at startup (ValidateOnStart);
the ViewComponent becomes an async builder taking an authorize(user, policy) callable,
standing in for IAuthorizationService.
"""

from __future__ import annotations

from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass
from typing import Any

from pydantic import BaseModel, Field, model_validator

Authorize = Callable[[Any, str], Awaitable[bool]]


class NavItem(BaseModel):
    title: str = ""
    url: str | None = None
    policy: str | None = None
    children: list[NavItem] = Field(default_factory=list)


class NavigationOptions(BaseModel):
    items: list[NavItem] = Field(default_factory=list)

    @model_validator(mode="after")
    def _validate(self) -> NavigationOptions:
        if not (len(self.items) > 0 and all(len(i.title) > 0 for i in self.items)):
            raise ValueError("Navigation needs at least one item with a title.")
        return self


@dataclass(frozen=True)
class MenuEntry:
    title: str
    url: str
    is_active: bool
    children: tuple[MenuEntry, ...]


class MainMenu:
    def __init__(self, options: Callable[[], NavigationOptions], authorize: Authorize) -> None:
        self._options = options  # IOptionsMonitor: read current value each call
        self._authorize = authorize

    async def invoke(self, user: Any, path: str | None) -> list[MenuEntry]:
        return await self._build(self._options().items, user, path or "/")

    async def _build(self, items: Iterable[NavItem], user: Any, path: str) -> list[MenuEntry]:
        entries: list[MenuEntry] = []
        for item in items:
            if item.policy is not None and not await self._authorize(user, item.policy):
                continue

            children = await self._build(item.children, user, path)
            if item.url is None and len(children) == 0:
                continue  # a group with nothing visible in it

            active = _is_active(item.url, path) or any(c.is_active for c in children)
            entries.append(MenuEntry(item.title, item.url or "#", active, tuple(children)))

        return entries


def _is_active(url: str | None, path: str) -> bool:
    if url is None:
        return False

    if url == "/":
        return path == "/"

    return path.casefold() == url.casefold() or path.casefold().startswith(url.casefold() + "/")


def add_navigation(config: Mapping[str, Any]) -> NavigationOptions:
    # Bind the "Navigation" section and validate on start (raises on bad config).
    return NavigationOptions.model_validate(config.get("Navigation", {}))

How it works

The menu is data. Adding a page to the menu is a configuration change, reviewed like any other, and the options are validated at startup so a broken section fails the deployment instead of the first request.

Each item names an authorization policy, the same policies that protect the controllers ([Authorize(Policy = "Finance")]). The view component asks IAuthorizationService whether the current user satisfies the policy, so the menu and the page security use one rule and can't drift. A group like "Billing" disappears when none of its children are visible.

IsActive compares whole path segments, so /invoices/42 highlights "Invoices" but /invoices-archive doesn't. A parent is active when any child is, which keeps the open section highlighted.

Because the component reads IOptionsMonitor<T>.CurrentValue, menu changes in appsettings.json show up without a restart.

Variations and pitfalls

  • A policy named in configuration but not registered makes AuthorizeAsync throw. Add a startup check that every Policy in the menu exists, using IAuthorizationPolicyProvider.GetPolicyAsync.
  • Hiding a link is not security. Every target still needs its own [Authorize] or filter; the menu just stops advertising what the user can't open.
  • For per-tenant or user-editable menus, load the items from a table and cache them (Chapter 3). The view component doesn't change.
  • Generate URLs from route names (Url.RouteUrl) if your paths change often; plain paths are easier for administrators to read.