iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
自我挑戰組

打造自己的Medium系列 第 19

Day19 JWT

  • 分享至 

  • xImage
  •  

雖然這裡已經有很多人寫過ASP.NET Core使用JWT,但我還是想紀錄自己的版本

安裝設定

1.安裝指令
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
2.建立jwtSettings.cs

public class JwtSettings
{
    public string Issuer { get; set; } = null!;
    public string Audience { get; set; } = null!;
    public string Key { get; set; } = null!;
}
  1. 設定appsettings.json
    這裡的Key長度跟選擇的加密方式有關
  "JWT": {
    "Key": "YourSecretKeyHere",
    "Issuer": "YourIssuer",
    "Audience": "YourAudience"
  }
  1. 在Program.cs加入
var jwtSettings = builder.Configuration.GetSection("JWT").Get<JwtSettings>()
    ?? throw new InvalidOperationException("JWT settings are missing");

builder.Services.AddSingleton(jwtSettings);
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = jwtSettings.Issuer,
        ValidAudience = jwtSettings.Audience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Key))
    };
});
app.UseAuthentication();
app.UseAuthorization();
  1. 修改swagger設定
builder.Services.AddOpenApiDocument(options =>
{
    options.PostProcess = document =>
    {
        document.Info = new NSwag.OpenApiInfo
        {
            Version = "v1",
            Title = "Leni API",
            Description = "An ASP.NET Core Web API for article platform"

        };
    };

    options.AddSecurity("JWT", new NSwag.OpenApiSecurityScheme
    {
        Type = NSwag.OpenApiSecuritySchemeType.Http,
        Scheme = "bearer",
        BearerFormat = "JWT",
        Name = "Authorization",
        In = NSwag.OpenApiSecurityApiKeyLocation.Header,
        Description = "Enter your JWT token"
    });


    options.OperationProcessors.Add(
        new NSwag.Generation.Processors.Security.AspNetCoreOperationSecurityScopeProcessor("JWT")
    );
});
  1. 設定生成token的方式
        private string GenerateJwtToken(User user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_jwtSettings.Key);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Account),
                    new Claim(ClaimTypes.Name, user.Name??String.Empty),
                    // 可加入更多自訂 Claims
                }),
                Expires = DateTime.UtcNow.AddHours(1),
                Issuer = _jwtSettings.Issuer,
                Audience = _jwtSettings.Audience,
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    // 這裡可以替換簽章演算法
                    SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

如何設定需要受權驗證

使用Microsoft.AspNetCore.Authorization
在Controller或單一API前加入[Authorize],就會自己驗證囉

如何拿取Token中的資料

使用System.Security.Claims
如果想要從Token解析出Account
可以在API涵式裡呼叫ClaimTypes.NameIdentifier

參考資源

Configure JWT bearer authentication in ASP.NET Core
使用 dotnet user-jwts 管理開發時期的 JWT Tokens 與 Signing key

作者的哈拉

小人退散/images/emoticon/emoticon05.gif


上一篇
Day18 Entity Framework Core
下一篇
Day20 LINQ
系列文
打造自己的Medium30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言