■ JWT 토큰을 생성하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; #region JWT 토큰 생성하기 - GenerateJWTToken(claimEnumerable, secretKey, issuer, audience) /// <summary> /// JWT 토큰 생성하기 /// </summary> /// <param name="claimEnumerable">클레임 열거 가능형</param> /// <param name="secretKey">비밀 키</param> /// <param name="issuer">발행자</param> /// <param name="audience">청취자</param> /// <returns>JWT 토큰</returns> public string GenerateJWTToken(IEnumerable<Claim> claimEnumerable, string secretKey, string issuer, string audience) { byte[] keyByteArray = Encoding.UTF8.GetBytes(secretKey); SymmetricSecurityKey symmetricSecurityKey = new(keyByteArray); SigningCredentials credentials = new(symmetricSecurityKey, SecurityAlgorithms.HmacSha256); JwtSecurityToken token = new ( issuer : issuer, audience : audience, claims : claimEnumerable, expires : DateTime.Now.AddHours(1), signingCredentials : credentials ); string tokenString = new JwtSecurityTokenHandler().WriteToken(token); return tokenString; } #endregion |