# Authorization

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Application Security
Source: https://www.devtutorials.ai/learn/blazor/application-security/authorization

> Decide what a user may do: protecting pages with [Authorize], AuthorizeRouteView, redirecting to login, AuthorizeView with Authorized and NotAuthorized content, role-based and claims-based authorization with policies, protecting API endpoints, and 401 vs 403.

## Authorization Overview

- **Authentication** (last lesson) finds out **who** the user is.
- **Authorization** decides what that user **may do**: which pages they may open, which buttons they see, which data they may change.
- Authorization always comes **after** authentication. First "who are you?", then "are you allowed?".

**Real-World Example:**

At the Tea Shop:

1. **Everyone** may see the menu.
2. **Logged-in customers** may see their own orders.
3. Only **staff** may open the kitchen dashboard.
4. Only **Gold** club members may claim a free chai.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-authz-doors">
  <title id="fig-authz-doors">Animation: a visitor walks past three doors. The Menu door is open to everyone. The My orders door checks: logged in? The Kitchen door checks: role Staff? A dot passes the first two doors and is stopped at the Kitchen door with a red cross.</title>
  <defs><marker id="fig-authz-doors-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="grn" x="20" y="40" width="170" height="110" rx="12" />
  <text className="t m" x="105" y="72" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Menu</text>
  <text className="t" x="105" y="96" textAnchor="middle" style={{ fontSize: 11 }}>everyone</text>
  <rect className="blu" x="235" y="40" width="170" height="110" rx="12" />
  <text className="t m" x="320" y="72" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>My orders</text>
  <text className="t" x="320" y="96" textAnchor="middle" style={{ fontSize: 11 }}>logged in?</text>
  <rect className="org" x="450" y="40" width="170" height="110" rx="12" />
  <text className="t m" x="535" y="72" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Kitchen</text>
  <text className="t" x="535" y="96" textAnchor="middle" style={{ fontSize: 11 }}>role Staff?</text>
  <text className="t m" x="535" y="132" textAnchor="middle" style={{ fontSize: 16, fontWeight: 700 }}>✗<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.6;0.65;1" dur="5s" repeatCount="indefinite" /></text>
  <text className="t" x="320" y="180" textAnchor="middle" style={{ fontSize: 11 }}>Ravi is a logged-in customer, so he gets in twice and is stopped once.</text>
  <circle r="8" cy="125" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="30;105;320;470;470" keyTimes="0;0.2;0.45;0.6;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Each door checks something different about the same user.</figcaption>
</figure>

In a Blazor app, you protect three places. This lesson covers each one:

| Place | Tool |
|---|---|
| A whole **page** | `[Authorize]` and `AuthorizeRouteView` |
| A **part** of a page | `<AuthorizeView>` |
| An **API endpoint** on the server | `[Authorize]` and `RequireAuthorization()` |

The code boxes use the pretend `TeaShopAuthStateProvider` from **Authentication** again, so you can log in with a button.

## Protecting Pages ([Authorize])

- An **attribute** is a label in square brackets that adds information to a class, like `[Required]` in **Form Validation**.
- Put **`@attribute [Authorize]`** at the top of a page, and only logged-in users may open it.
- It needs `@using Microsoft.AspNetCore.Authorization` (or put that line in `_Imports.razor` once).
- `[Authorize]` works on **pages** (components with `@page`). For parts of a page, use `<AuthorizeView>` (later in this lesson).

<p>Only logged-in users can see this page.</p>
`}
/>

- On the server, the authorization middleware checks `[Authorize]` **before** the page runs (see **Middleware Pipeline**).
- In the browser, during interactive navigation, a component called **`AuthorizeRouteView`** checks it. That is the next section.

## AuthorizeRouteView

- The **Router** in `Routes.razor` finds the page for the address. Normally a **`RouteView`** then shows it.
- **`AuthorizeRouteView`** is a `RouteView` that first checks the page's `[Authorize]` attribute.
- If the user is allowed, it shows the page. If not, it shows its **`<NotAuthorized>`** content instead.
- It needs the cascading authentication state, so `AddCascadingAuthenticationState()` must be in `Program.cs`.

This is `Routes.razor` in the Identity template (`dotnet new blazor -au Individual`):

`}
/>

In the below example, two buttons play the part of the Router: they choose a page and build its **`RouteData`** (the page type plus its route values). `MyOrders` has `[Authorize]`, `Menu` does not. Open `/my-orders`, then log in and open it again.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (staff)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>
<hr />
<button @onclick="() => page = typeof(Menu)">Open /menu</button>
<button @onclick="() => page = typeof(MyOrders)">Open /my-orders</button>

              <p>Please log in to see this page.</p>

@code {
      // In a real app, the Router makes RouteData from the address
      private Type page = typeof(Menu);
      private RouteData Route => new(page, new Dictionary<string, object?>());

      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Components/Pages/Menu.razor": `@page "/menu"

<h3>Menu</h3>
<p>Masala chai, Ginger tea, Lemon tea</p>
`,
    "Components/Pages/MyOrders.razor": `@page "/my-orders"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

<h3>My orders</h3>
<p>Order #12: 2 x Masala chai</p>
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- While logged out, `/my-orders` shows the `<NotAuthorized>` text. The page code does not run at all.
- After you log in, the same page appears.

Put `@using Microsoft.AspNetCore.Authorization` in `Components/_Imports.razor` once. Then every page can use `[Authorize]` without its own `@using` line.

## Redirecting Unauthenticated Users

Showing "please log in" works, but users like to be **taken** to the login page, and brought back afterwards.

- The Identity template puts **`<RedirectToLogin />`** inside `<NotAuthorized>`.
- It sends the user to `Account/Login` and adds a **`returnUrl`**: the page they wanted. After login, the login page sends them back there.

<figure className="blz-fig">
<svg viewBox="0 0 640 170" role="img" aria-labelledby="fig-authz-redirect">
  <title id="fig-authz-redirect">Animation: 1. A logged-out user opens /my-orders. 2. They are sent to /Account/Login?returnUrl=/my-orders. 3. After a correct login, they are sent back to /my-orders, which now opens.</title>
  <defs><marker id="fig-authz-redirect-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="org" x="10" y="60" width="170" height="70" rx="12" />
  <text className="t m" x="95" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>/my-orders</text>
  <text className="t" x="95" y="110" textAnchor="middle" style={{ fontSize: 10 }}>not logged in</text>
  <rect className="pur" x="235" y="60" width="170" height="70" rx="12" />
  <text className="t m" x="320" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>/Account/Login</text>
  <text className="t" x="320" y="110" textAnchor="middle" style={{ fontSize: 10 }}>?returnUrl=/my-orders</text>
  <rect className="grn" x="460" y="60" width="170" height="70" rx="12" />
  <text className="t m" x="545" y="90" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>/my-orders</text>
  <text className="t" x="545" y="110" textAnchor="middle" style={{ fontSize: 10 }}>opens</text>
  <path className="line" d="M180 95 H231" markerEnd="url(#fig-authz-redirect-a)" />
  <path className="line" d="M405 95 H456" markerEnd="url(#fig-authz-redirect-a)" />
  <text className="t" x="207" y="50" textAnchor="middle" style={{ fontSize: 10 }}>redirect</text>
  <text className="t" x="432" y="50" textAnchor="middle" style={{ fontSize: 10 }}>log in, go back</text>
  <circle r="8" cy="150" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="95;95;320;320;545;545" keyTimes="0;0.15;0.4;0.6;0.85;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Not logged in? Go to login, then come back to the page you wanted.</figcaption>
</figure>

- `forceLoad: true` makes a full page load, so the static login page and the server can set the cookie.
- For static (non-interactive) requests, the **cookie scheme** does the same redirect by itself, using its `LoginPath` option (see **Authentication**).

## Showing Content Conditionally (AuthorizeView)

- **`<AuthorizeView>`** shows or hides **part** of a page, based on the user.
- Use it for things like a "Log in" link for guests and a "Hello, Ravi" greeting for logged-in users.
- Inside it, **`context`** is the `AuthenticationState`, so `context.User` is the current user.

### Authorized and NotAuthorized Content

| Part | Shown when |
|---|---|
| `<Authorized>` | The user is allowed (here: logged in) |
| `<NotAuthorized>` | The user is not allowed |
| `<Authorizing>` | While the check is still running (optional) |

In the below example, the greeting changes when you log in and out.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (staff)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

              <p>Hello, @context.User.Identity?.Name! Here are your orders.</p>
              <p>Hello, guest! Please log in to see your orders.</p>

@code {
      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- If you only need the "allowed" part, you can write the content directly inside `<AuthorizeView>`, without `<Authorized>`.

`<AuthorizeView>` only hides things on the **screen**. Anyone can still call your server directly. Always protect the page itself with `[Authorize]`, and the data with protected **API endpoints**.

## Role-Based Authorization

- A **role** is a group that users belong to, like `Customer`, `Staff` or `Manager`.
- A user's roles are **role claims** (`ClaimTypes.Role`), so they travel inside the login cookie.
- Check roles in three places:

| Where | Code |
|---|---|
| A page | `@attribute [Authorize(Roles = "Staff")]` |
| Part of a page | `<AuthorizeView Roles="Staff">` |
| C# code | `user.IsInRole("Staff")` |

- `Roles = "Staff, Manager"` (with a comma) means **either** role is enough.
- With Identity, add role support with `.AddRoles<IdentityRole>()` after `AddIdentityCore`, and give a user a role with `await UserManager.AddToRoleAsync(user, "Staff");`.

In the below example, the kitchen link is only for the `Staff` role. Ravi is a customer, Meena is staff.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (staff)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

          <p>Logged in as @context.User.Identity?.Name</p>

              <p><b>Kitchen dashboard:</b> 3 orders waiting</p>
              <p>The kitchen is for staff only.</p>

@code {
      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

## Claims-Based Authorization

Roles are simple, but sometimes the rule is about **other facts** about the user: a club level, a country, an employee number. That is **claims-based** authorization.

- You write the rule once, as a **policy**: a named rule, like `"GoldMember"`.
- Register policies in `Program.cs` with **`AddAuthorization`**. `RequireClaim("TeaClub", "Gold")` means "must have a TeaClub claim with the value Gold".
- Then use the policy name: `[Authorize(Policy = "GoldMember")]`, `<AuthorizeView Policy="GoldMember">` or in code.

{
      options.AddPolicy("GoldMember", policy =>
          policy.RequireClaim("TeaClub", "Gold"));

      options.AddPolicy("StaffOrManager", policy =>
          policy.RequireRole("Staff", "Manager"));
});
`}
/>

- A policy can also hold role rules (`RequireRole`) and more than one rule. All of them must pass.
- The code boxes have no `Program.cs`, so their policies live in an `AuthPolicies.Configure` method. In your app you pass it the same way: `builder.Services.AddAuthorization(AuthPolicies.Configure);`

In the below example, Ravi logs in with the claim `TeaClub = Gold`, and Meena without it. Only Gold members see the reward.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (no club)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

              <p>Free chai for you, @context.User.Identity?.Name!</p>
              <p>Join the Gold club to get a free chai.</p>

@code {
      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Auth/AuthPolicies.cs": `namespace BlazorApp.Auth;

using Microsoft.AspNetCore.Authorization;

public static class AuthPolicies
{
      // In Program.cs: builder.Services.AddAuthorization(AuthPolicies.Configure);
      public static void Configure(AuthorizationOptions options)
      {
          // Only users with the claim TeaClub = Gold
          options.AddPolicy("GoldMember", policy =>
              policy.RequireClaim("TeaClub", "Gold"));
      }
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

### Checking a Policy in Code

Sometimes the check belongs inside a method, for example when a button is clicked. Inject **`IAuthorizationService`** and call **`AuthorizeAsync(user, "PolicyName")`**. Its result has **`Succeeded`**.

In the below example, log in first (the line under the buttons shows who you are). Then the **Claim** button checks the `GoldMember` policy before it gives out the reward.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (no club)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

          <Authorized><p>Logged in as @context.User.Identity?.Name</p></Authorized>
          <NotAuthorized><p>Not logged in</p></NotAuthorized>

<button @onclick="ClaimReward">Claim a free chai</button>
<p>@message</p>

@code {
      private string message = "";

      private async Task ClaimReward()
      {
          var user = (await AuthProvider.GetAuthenticationStateAsync()).User;
          var result = await AuthService.AuthorizeAsync(user, "GoldMember");

          message = result.Succeeded
              ? "Enjoy your free chai!"
              : "Sorry, rewards are for Gold members.";
      }

      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Auth/AuthPolicies.cs": `namespace BlazorApp.Auth;

using Microsoft.AspNetCore.Authorization;

public static class AuthPolicies
{
      // In Program.cs: builder.Services.AddAuthorization(AuthPolicies.Configure);
      public static void Configure(AuthorizationOptions options)
      {
          // Only users with the claim TeaClub = Gold
          options.AddPolicy("GoldMember", policy =>
              policy.RequireClaim("TeaClub", "Gold"));
      }
}
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

## Protecting API Endpoints

Hiding a button does not stop someone from calling the API directly. So the **server** must check too.

- On a controller or an action (see **API Integration**), add **`[Authorize]`**, `[Authorize(Roles = "Staff")]` or `[Authorize(Policy = "GoldMember")]`.
- **`[AllowAnonymous]`** opens one action again, inside a protected controller.
- For minimal API endpoints (`app.MapGet`), add **`.RequireAuthorization()`**, with or without a policy name.

          Ok(new[] { $"Order for {User.Identity!.Name}" });

      [HttpGet("all")]
      [Authorize(Roles = "Staff")]              // this action: staff only
      public IActionResult GetAll() =>
          Ok(new[] { "Every order" });

      [HttpGet("menu")]
      [AllowAnonymous]                          // this action: everyone
      public IActionResult GetMenu() =>
          Ok(new[] { "Masala", "Ginger" });
}
`}
/>

      options.AddPolicy("GoldMember", policy => policy.RequireClaim("TeaClub", "Gold")));

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapGet("/api/rewards", () => new { Reward = "Free chai" })
      .RequireAuthorization("GoldMember");
`}
/>

Here is what the server answers, first with no login cookie, then logged in as Ravi (a customer, not Gold):

For API endpoints, .NET 10 answers **401** and **403** directly. For pages, the cookie scheme **redirects** to the login page (or the access denied page) instead.

## 401 Unauthorized vs. 403 Forbidden

These two status codes are easy to mix up, because "Unauthorized" sounds like "not allowed".

| Code | Name | Real meaning | Fix for the user |
|---|---|---|---|
| **401** | Unauthorized | "I do not know **who** you are." (Not logged in, or the login expired) | Log in |
| **403** | Forbidden | "I know who you are, but you are **not allowed**." | Ask for the right role or claim. Logging in again will not help |

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-authz-401-403">
  <title id="fig-authz-401-403">Two cards. 401 Unauthorized: a person with a question mark, the server asks: who are you? Fix: log in. 403 Forbidden: a person with a name badge, Ravi, the server says: I know you, but no. Fix: needs the Staff role.</title>
  <defs><marker id="fig-authz-401-403-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="org" x="10" y="15" width="300" height="160" rx="14" />
  <text className="t m" x="160" y="45" textAnchor="middle" style={{ fontSize: 16, fontWeight: 700 }}>401 Unauthorized</text>
  <circle cx="160" cy="88" r="22" className="box" />
  <text className="t m" x="160" y="96" textAnchor="middle" style={{ fontSize: 20, fontWeight: 700 }}>?</text>
  <text className="t" x="160" y="135" textAnchor="middle" style={{ fontSize: 12 }}>"Who are you?"</text>
  <text className="t m" x="160" y="158" textAnchor="middle" style={{ fontSize: 11 }}>Fix: log in</text>
  <rect className="pur" x="330" y="15" width="300" height="160" rx="14" />
  <text className="t m" x="480" y="45" textAnchor="middle" style={{ fontSize: 16, fontWeight: 700 }}>403 Forbidden</text>
  <rect className="box" x="440" y="70" width="80" height="36" rx="8" />
  <text className="t m" x="480" y="93" textAnchor="middle" style={{ fontSize: 12 }}>Ravi</text>
  <text className="t" x="480" y="135" textAnchor="middle" style={{ fontSize: 12 }}>"I know you, but no."</text>
  <text className="t m" x="480" y="158" textAnchor="middle" style={{ fontSize: 11 }}>Fix: needs the Staff role</text>
</svg>
<figcaption>401 is about who you are. 403 is about what you may do.</figcaption>
</figure>

In a Blazor page, `<NotAuthorized>` gets the user as `context`. Check `IsAuthenticated` to tell the two cases apart. In the below example, open the kitchen page as a guest, then as Ravi, then as Meena.

<button @onclick='() => Provider.LogIn("Meena", "Staff")'>Meena (staff)</button>
<button @onclick="() => Provider.LogOut()">Log out</button>

              @if (context.User.Identity?.IsAuthenticated == true)
              {
                  <p>403: Sorry @context.User.Identity.Name, the kitchen is for staff only.</p>
              }
              else
              {
                  <p>401: Please log in first.</p>
              }

@code {
      private RouteData Route => new(typeof(Kitchen), new Dictionary<string, object?>());

      // The pretend provider, for the buttons
      private TeaShopAuthStateProvider Provider => (TeaShopAuthStateProvider)AuthProvider;
}
`,
    "Components/Pages/Kitchen.razor": `@page "/kitchen"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles = "Staff")]

<h3>Kitchen</h3>
<p>3 orders waiting</p>
`,
    "Auth/TeaShopAuthStateProvider.cs": `namespace BlazorApp.Auth;

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;

// A pretend provider (see Authentication). In a real app, the user comes from the login cookie.
public class TeaShopAuthStateProvider : AuthenticationStateProvider
{
      private ClaimsPrincipal user = new(new ClaimsIdentity());   // nobody yet

      public override Task<AuthenticationState> GetAuthenticationStateAsync() =>
          Task.FromResult(new AuthenticationState(user));

      public void LogIn(string name, string role, params Claim[] extraClaims)
      {
          var claims = new List<Claim>
          {
              new(ClaimTypes.Name, name),
              new(ClaimTypes.Role, role),
          };
          claims.AddRange(extraClaims);
          user = new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies"));
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }

      public void LogOut()
      {
          user = new ClaimsPrincipal(new ClaimsIdentity());
          NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
      }
}
`,
  }}
/>

- The Identity template sends 403 cases to its `Account/AccessDenied` page.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Only hiding a button with `<AuthorizeView>` | Hidden means protected | Also protect the page with `[Authorize]` and the API with `[Authorize]` | Anyone can still call the API directly |
| `[Authorize]` on a child component (no `@page`) | It works on every component | Use it on pages. Use `<AuthorizeView>` for parts | The check is ignored |
| Using `RouteView` instead of `AuthorizeRouteView` | Pages check `[Authorize]` by themselves | Use `AuthorizeRouteView` in `Routes.razor` | Interactive navigation shows protected pages |
| No `AddCascadingAuthenticationState()` | Authorization finds the user by itself | Add it in `Program.cs` | `AuthorizeView` and `AuthorizeRouteView` throw errors |
| Using a policy name that is not registered | Any name works | Register it with `AddPolicy` first | "The AuthorizationPolicy named ... was not found" |
| Returning 401 to a logged-in user who lacks a role | 401 means "not allowed" | Use 403 for "known, but not allowed" | Users are asked to log in again for nothing |

</div>

## Check Yourself

## Exercises

## What to Remember

- **Authorization** decides what a known user may do. It comes after authentication.
- Protect a page with `@attribute [Authorize]`. **`AuthorizeRouteView`** in `Routes.razor` checks it and shows `<NotAuthorized>`, often `<RedirectToLogin />` with a `returnUrl`.
- **`<AuthorizeView>`** shows `<Authorized>` or `<NotAuthorized>` content for part of a page. It only hides things; it does not protect data.
- **Roles**: `[Authorize(Roles = "Staff")]`, `<AuthorizeView Roles="Staff">`, `user.IsInRole("Staff")`.
- **Claims**: register a policy with `AddPolicy` and `RequireClaim`, then use `Policy = "..."`, or check it in code with `IAuthorizationService.AuthorizeAsync`.
- Protect **API endpoints** with `[Authorize]` and `.RequireAuthorization()`. `[AllowAnonymous]` opens one action again.
- **401** means "who are you?" (log in). **403** means "I know you, but no".

Next: **Threat Protection**
