哈囉大家好!
昨天在AuthController完成了向前端發送Session Token的功能,接下來要讓未來其他API知道如何在Controller中接收和驗證Session Token。
在Program.cs檔案中新增AddAuthentication
和AddJwtBearer
服務,以及配置驗證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();
確定配置完認證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()
{
//...
}
}
/Auth/google-login
/Records/all-records
),都會在Authorization: Bearer Header中戴上這個Token。UseAuthentication
會先驗證Session Token是否有效、是否過期以及Issuer和Audience是否符合配置。