Authorization
By Syncfusion®, Inc. · Last updated
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.
What you will learn
- Protect pages with [Authorize] and AuthorizeRouteView
- Redirect users to login and show content with AuthorizeView
- Use role-based and claims-based authorization
- Protect API endpoints and tell 401 from 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:
- Everyone may see the menu.
- Logged-in customers may see their own orders.
- Only staff may open the kitchen dashboard.
- Only Gold club members may claim a free chai.
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.
Menu everyone
My orders logged in?
Kitchen role Staff? ✗ Ravi is a logged-in customer, so he gets in twice and is stopped once.
Each door checks something different about the same user.
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.razoronce). [Authorize]works on pages (components with@page). For parts of a page, use<AuthorizeView>(later in this lesson).
- On the server, the authorization middleware checks
[Authorize]before the page runs (see Middleware Pipeline). - In the browser, during interactive navigation, a component called
AuthorizeRouteViewchecks it. That is the next section.
AuthorizeRouteView
- The Router in
Routes.razorfinds the page for the address. Normally aRouteViewthen shows it. AuthorizeRouteViewis aRouteViewthat 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 inProgram.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.
- While logged out,
/my-ordersshows 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/Loginand adds areturnUrl: the page they wanted. After login, the login page sends them back there.
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.
/my-orders not logged in
/Account/Login ?returnUrl=/my-orders
/my-orders opens
redirect log in, go back
Not logged in? Go to login, then come back to the page you wanted.
forceLoad: truemakes 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
LoginPathoption (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,
contextis theAuthenticationState, socontext.Useris 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.
- 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,StafforManager. - 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>()afterAddIdentityCore, and give a user a role withawait UserManager.AddToRoleAsync(user, "Staff");.
In the below example, the kitchen link is only for the Staff role. Ravi is a customer, Meena is staff.
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.cswithAddAuthorization.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.
- 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 anAuthPolicies.Configuremethod. 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.
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.
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.
Here is what the server answers, first with no login cookie, then logged in as Ravi (a customer, not Gold):
Click Next to see each request and its answer.
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 |
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.
401 Unauthorized
? "Who are you?" Fix: log in
403 Forbidden
Ravi "I know you, but no." Fix: needs the Staff role
401 is about who you are. 403 is about what you may do.
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.
- The Identity template sends 403 cases to its
Account/AccessDeniedpage.
Common mistakes
| 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 |
Check Yourself
Exercises
What to Remember
- Authorization decides what a known user may do. It comes after authentication.
- Protect a page with
@attribute [Authorize].AuthorizeRouteViewinRoutes.razorchecks it and shows<NotAuthorized>, often<RedirectToLogin />with areturnUrl. <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
AddPolicyandRequireClaim, then usePolicy = "...", or check it in code withIAuthorizationService.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