iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
佛心分享-SideProject30

30天的旅程!從學習C#到開發小專案系列 第 23

DAY 23 - 配置JWT Bearer 認證中介軟體(Middleware)

  • 分享至 

  • xImage
  •  

哈囉大家好!
昨天在AuthController完成了向前端發送Session Token的功能,接下來要讓未來其他API知道如何在Controller中接收和驗證Session Token。

在Program.cs中配置JWT Bearer認證Middleware

在Program.cs檔案中新增AddAuthenticationAddJwtBearer服務,以及配置驗證Token需要的參數:

...
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
...

// 讀取appsettings.json檔中JWT的配置
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var secret = jwtSettings["Secret"] ?? throw new InvalidOperationException("JWT Secret not configured.");
var issuer = jwtSettings["Issuer"];
var audience = jwtSettings["Audience"];

// 新增Authentication 服務
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    // 要驗證的參數
    options.TokenValidationParameters = new TokenValidationParameters
    {
        // 驗證簽名secret key
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)),

        // 驗證發行者(iss)
        ValidateIssuer = true,
        ValidIssuer = issuer,

        // 驗證受眾(aud)
        ValidateAudience = true,
        ValidAudience = audience,

        // 驗證Token的有限期限
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero 
    };
});
app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

先建立一個需要授權的Controller-RecordsController

確定配置完認證middleware後,可以在其他需要使用者登入的API endpoint使用[Authorize]property。
當請求發送給這些API endpoint時,API就會自動檢查請求Header中的Session Token:(這裡舉例處理使用者建立紀錄的API: RecordsController)

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization; 
using System.Security.Claims;

namespace GoDutchBackend.Controllers;

[Authorize] // RecordsController需要有效的Session Token才能處理請求
[ApiController]
[Route("[controller]")]
public class RecordsController : ControllerBase
{
    private readonly AppDbContext _dbContext; 
    
    public RecordsController(AppDbContext dbContext)
     {
         _dbContext = dbContext;
    }
    
    [HttpGet("all-records")]
    public IActionResult GetAllRecords()
    {
        //...
    }
}

驗證流程整理

  1. 使用者點擊Google帳戶登入按鈕,得到Google傳送回來的Google ID Token。
  2. 前端透過POST Request將Google ID Token送到/Auth/google-login
  3. AuthController驗證Google ID Token,再用appsettings.json中配置的Secret來簽發Session Token。
  4. 前端儲存後端回傳的Session Token。(例如:localStorage)
  5. 之後前端發送的所有請求(例如剛剛舉例的/Records/all-records),都會在Authorization: Bearer Header中戴上這個Token。
  6. 在RecordsController開始處理請求前,配置的moddleware UseAuthentication會先驗證Session Token是否有效、是否過期以及Issuer和Audience是否符合配置。
  7. 若Session Token有效,就會進入對應的method進行接下來的處理。

上一篇
DAY 22 - 生成Session Token並註冊驗證服務
下一篇
DAY 24 - 解決CORS(跨域資源共享)問題
系列文
30天的旅程!從學習C#到開發小專案24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言