使用 OAuth Token Introspection

.NET 8 的專案為範例

範例

  1. 安裝 IdentityModel.AspNetCore.OAuth2Introspection Nuget Packages

    版本為 6.2.0

    1
    Install-Package IdentityModel.AspNetCore.OAuth2Introspection
  2. 配置 Token Introspection

    Program.cs 新增下列程式碼:

    1
    2
    3
    4
    5
    6
    7
    8
    builder.Services
    .AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
    .AddOAuth2Introspection(options =>
    {
    options.ClientId = configuration["Auth:ClientId"];
    options.ClientSecret = configuration["Auth:ClientSecret"];
    options.IntrospectionEndpoint = configuration["Auth:IntrospectionEndpoint"];
    });
  3. 配置 Global Authorization Policy

    讓系統預設為必須經過驗證,不需要驗證的再使用 AllowAnonymous attribute。

    Program.cs 新增下列程式碼:

    1
    2
    3
    4
    5
    6
    builder.Services.AddAuthorization(options =>
    {
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();
    });
  4. 取得 Token Claims

    驗證通過後,Token Claims 會儲存在 HttpContext,在 Controller 裡使用 ControllerBase.HttpContext 來存取。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    using Microsoft.AspNetCore.Mvc;
    using Purchasing.UseCases.Dtos;

    namespace Purchasing.Api.Controllers
    {
    [Route("[controller]")]
    [ApiController]
    public class PurchaseOrdersController : ControllerBase
    {
    [HttpGet]
    public async Task<ActionResult<List<PurchaseOrderDto>>> ListPurchaseOrdersAsync()
    {
    var claim = HttpContext.User.FindFirst("claim_name").Value;

    // ...
    }
    }
    }

    不同情境有不同的存取方式,可參考 Access HttpContext in ASP.NET Core