簽發包含 admin
與 user
角色的 JWT Token
調整 API Controller 加入 [Authorize(Roles = "admin, manager")]
屬性
設定 admin
或 manager
都可以授權存取此 API
using Microsoft.AspNetCore.Authorization;
[Authorize(Roles = "admin, manager")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{ ... }
建立 JWT Token 並在 Token 寫入 role
的 Claims
dotnet user-jwts create --role admin --role user
重新啟動網站 (一定要啟動在 Development
環境喔)
dotnet run
透過 cURL 發出要求
curl -i -H "Authorization: Bearer {token}" http://localhost:5000/WeatherForecast
執行結果,你將會得到 HTTP/1.1 200 OK
回應!
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Fri, 28 Apr 2023 13:20:48 GMT
Server: Kestrel
Transfer-Encoding: chunked
[{"date":"2023-04-29","temperatureC":-18,"temperatureF":0,"summary":"Bracing"},{"date":"2023-04-30","temperatureC":54,"temperatureF":129,"summary":"Bracing"},{"date":"2023-05-01","temperatureC":51,"temperatureF":123,"summary":"Balmy"},{"date":"2023-05-02","temperatureC":35,"temperatureF":94,"summary":"Warm"},{"date":"2023-05-03","temperatureC":5,"temperatureF":40,"summary":"Chilly"}]
建立 JWT Token 並在 Token 寫入 role
的 Claims(只有 user
角色)
dotnet user-jwts create --role user
重新啟動網站 (一定要啟動在 Development
環境喔)
dotnet run
透過 cURL 發出要求
curl -i -H "Authorization: Bearer {token}" http://localhost:5000/WeatherForecast
執行結果,你將會得到 HTTP/1.1 200 OK
回應!
HTTP/1.1 403 Forbidden
Content-Length: 0
Date: Fri, 28 Apr 2023 14:18:58 GMT
Server: Kestrel
簽發包含 myapi:secrets
範圍(Scope)的 JWT Token
簽發 JWT Token 的時候,可以依據簽發的 scope
claim 來限縮特定 JWT Token 的授權範圍,當然我們在程式中也需要定義相對應的 Policy 授權政策。
先在 DI 容器中宣告政策:(Program.cs
)
builder.Services.AddAuthentication("Bearer").AddJwtBearer();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("MyAPIOnly", policy => policy.RequireClaim("scope","myapi:secrets"));
options.AddPolicy("AdminOnly", policy => policy.RequireClaim(ClaimTypes.Role, "admin"));
options.AddPolicy("UserOnly", policy => policy.RequireClaim(ClaimTypes.Role, "user"));
});
建立 JWT Token 並在 Token 寫入 scope
的 Claims(只有 myapi:secrets
範圍)
dotnet user-jwts create --scope "myapi:secrets" --role "admin"
調整 API Controller 加入 [Authorize(Roles = "admin, manager", Policy = "MyAPIOnly")]
屬性
using Microsoft.AspNetCore.Authorization;
[Authorize(Roles = "admin, manager", Policy = "MyAPIOnly")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{ ... }
注意: 上述語法需要這樣理解,角色為 admin
或 manager
,而且同時要符合 MyAPIOnly
政策!