ZetCode

ASP.NET UseAuthorization

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 ASP.NET 8 中的 UseAuthorization 中间件。此组件对于在 Web 应用程序中实现身份验证和授权至关重要。

ASP.NET 提供了一个强大的安全系统,该系统将身份验证和授权分开。UseAuthorization 支持基于策略的访问控制,以保护您的应用程序资源。

基本定义

ASP.NET 中的 UseAuthorization 中间件处理请求的授权。它与身份验证中间件协同工作,以保护您的应用程序终结点。

授权决定已通过身份验证的用户可以执行什么操作。它通常添加到 UseAuthentication 之后、终结点路由之前的中建件管道中。

UseAuthorization 根据当前用户评估授权策略。这些策略可以是基于角色的、基于声明的或自定义要求的。

ASP.NET UseAuthorization 示例

以下示例演示了一个具有授权设置的基本 ASP.NET 应用程序。

Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddAuthentication("Cookies")
    .AddCookie("Cookies", options =>
    {
        options.LoginPath = "/Account/Login";
        options.AccessDeniedPath = "/Account/AccessDenied";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => 
        policy.RequireRole("Admin"));
        
    options.AddPolicy("Over18", policy => 
        policy.RequireClaim("Age", "18"));
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

这设置了一个具有 Cookie 身份验证和两个授权策略的 ASP.NET 应用程序。AdminOnly 策略要求用户具有 Admin 角色。

Over18 策略要求用户具有值为 18 的 Age 声明。UseAuthorization 放置在中建件管道的 UseAuthentication 之后。

Controllers/HomeController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult MembersOnly()
    {
        return View();
    }

    [Authorize(Policy = "AdminOnly")]
    public IActionResult AdminDashboard()
    {
        return View();
    }

    [Authorize(Policy = "Over18")]
    public IActionResult AdultContent()
    {
        return View();
    }
}

此控制器演示了不同的授权场景。MembersOnly 操作要求任何已通过身份验证的用户,使用基本的 [Authorize] 属性。

AdminDashboard 操作使用我们在 Program.cs 中定义的 AdminOnly 策略。只有具有 Admin 角色的用户才能访问此终结点。

AdultContent 操作使用 Over18 策略,要求用户将 Age 声明设置为 18。[Authorize] 属性将这些策略应用于特定的操作。

Views/Account/Login.cshtml
@{
    ViewData["Title"] = "Login";
}

<h2>Login</h2>

<form method="post">
    <div>
        <label>Username</label>
        <input name="username" />
    </div>
    <div>
        <label>Password</label>
        <input name="password" type="password" />
    </div>
    <button type="submit">Login</button>
</form>

此简单的登录视图收集凭据。在实际应用程序中,您需要将这些凭据与用户存储进行验证,并颁发身份验证 Cookie。

来源

Microsoft ASP.NET 授权文档

在本文中,我们探讨了 ASP.NET 8 中的 UseAuthorization 中间件。此强大功能支持灵活的安全策略来保护您的应用程序资源。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 ASP.NET 教程