使用 OAuth Token Introspection
用 .NET 8
的專案為範例
範例
安裝
IdentityModel.AspNetCore.OAuth2Introspection
Nuget Packages版本為
6.2.0
1
Install-Package IdentityModel.AspNetCore.OAuth2Introspection
配置
Token Introspection
在
Program.cs
新增下列程式碼:1
2
3
4
5
6
7
8builder.Services
.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
.AddOAuth2Introspection(options =>
{
options.ClientId = configuration["Auth:ClientId"];
options.ClientSecret = configuration["Auth:ClientSecret"];
options.IntrospectionEndpoint = configuration["Auth:IntrospectionEndpoint"];
});配置
Global Authorization Policy
讓系統預設為必須經過驗證,不需要驗證的再使用
AllowAnonymous
attribute。在
Program.cs
新增下列程式碼:1
2
3
4
5
6builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});取得
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
18using Microsoft.AspNetCore.Mvc;
using Purchasing.UseCases.Dtos;
namespace Purchasing.Api.Controllers
{
[ ]
[ ]
public class PurchaseOrdersController : ControllerBase
{
[ ]
public async Task<ActionResult<List<PurchaseOrderDto>>> ListPurchaseOrdersAsync()
{
var claim = HttpContext.User.FindFirst("claim_name").Value;
// ...
}
}
}不同情境有不同的存取方式,可參考 Access HttpContext in ASP.NET Core。