全书目录

第十五篇:ASP.NET Core 完全指南 —— 国家级综合服务枢纽宇宙

第十一章:认证与授权 —— 先验明身份,再判断权限

1 分钟 103 字 第 300 / 962 个阅读单元

这是很多人最容易混淆的两件事:

text
Authentication(认证)= 你是谁
Authorization(授权)= 你能做什么

放进枢纽类比里:

text
认证 = 核验身份证、通行证
授权 = 判断你能不能进这个办公区、能不能办这项业务
#基本配置
csharp
builder.Services
    .AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://identity.example.com";
        options.Audience = "city-hub-api";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("OfficerOnly", policy =>
    {
        policy.RequireRole("Officer");
    });
});
csharp
app.UseAuthentication();
app.UseAuthorization();
#保护窗口

Controller 写法:

csharp
[Authorize(Policy = "OfficerOnly")]
[ApiController]
[Route("api/internal-reviews")]
public class InternalReviewsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() => Ok();
}

Minimal API 写法:

csharp
app.MapGet("/me", (ClaimsPrincipal user) =>
{
    return Results.Ok(new
    {
        name = user.Identity?.Name
    });
}).RequireAuthorization();
#顺序不能错

一定是:

text
UseAuthentication()
        ->
UseAuthorization()

因为你得先知道“他是谁”,才能判断“他有没有权限”。