Section 1 of 6
Authorization Fundamentals
🎯 What You'll Learn
- What is authorization
- Authorization vs authentication
- [Authorize] attribute
- AllowAnonymous
- Authorization middleware
What is Authorization?
Authorization determines what an authenticated user is allowed to do. It controls access to resources based on user identity, roles, claims, or policies.
💡 Remember
Authentication = "Who are you?" (Identity)
Authorization = "What can you do?" (Permissions)
Authorization Middleware
Program.cs
C#
var app = builder.Build();
// Order matters!
app.UseAuthentication(); // First: Who are you?
app.UseAuthorization(); // Second: What can you do?
app.Run();
[Authorize] Attribute
The [Authorize] attribute restricts access to authenticated users only.
Controller Level
Protect Entire Controller
C#
[Authorize]
public class DashboardController : Controller
{
public IActionResult Index()
{
return View();
}
}
Action Level
Protect Specific Action
C#
public class HomeController : Controller
{
public IActionResult Index()
{
return View(); // Public
}
[Authorize]
public IActionResult Profile()
{
return View(); // Requires authentication
}
}
Razor Pages
Protect Razor Page
C#
[Authorize]
public class ProfileModel : PageModel
{
public void OnGet() { }
}
[AllowAnonymous] Attribute
Allows anonymous access to specific actions even when controller is protected.
Allow Anonymous Access
C#
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public IActionResult Login()
{
return View(); // Public access
}
public IActionResult Profile()
{
return View(); // Requires authentication
}
}
Global Authorization
Require authentication for all endpoints by default.
Program.cs
C#
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
Authorization in Views
Check Authorization in Razor
HTML
@if (User.Identity?.IsAuthenticated == true)
{
<a href="/dashboard">Dashboard</a>
}
@else
{
<a href="/login">Login</a>
}
InvenTrack Example
ProductsController.cs
C#
[Authorize]
public class ProductsController : Controller
{
// All actions require authentication
public IActionResult Index()
{
var products = _context.Products.ToList();
return View(products);
}
public IActionResult Create()
{
return View();
}
}
Key Takeaways
- Authorization: Controls what users can do
- [Authorize]: Requires authentication
- [AllowAnonymous]: Allows public access
- UseAuthorization(): Must come after UseAuthentication()
- Global authorization: Require auth by default
- View checks: User.Identity?.IsAuthenticated