1. NuGet 패키지 설치
JWT 라이브러리를 NuGet을 통해 프로젝트에 추가합니다. JWT 패키지를 설치해야 합니다.
2. JWT 헬퍼 클래스 작성
using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
namespace ProjectName.Tool
{
public class JwtTokenHelper
{
private static readonly IJwtAlgorithm Algorithm = new HMACSHA256Algorithm();
private static readonly IJsonSerializer Serializer = new JsonNetSerializer();
private static readonly IBase64UrlEncoder UrlEncoder = new JwtBase64UrlEncoder();
private static readonly IDateTimeProvider DateTimeProvider = new UtcDateTimeProvider();
private const string SecretKey = "your-secure-secret-key-here";
public static string GenerateToken(Dictionary<string, object> claims)
{
var encoder = new JwtEncoder(Algorithm, Serializer, UrlEncoder);
return encoder.Encode(claims, SecretKey);
}
public static bool VerifyToken(string token, out string decodedPayload, out string resultMessage)
{
decodedPayload = string.Empty;
try
{
var validator = new JwtValidator(Serializer, DateTimeProvider);
var decoder = new JwtDecoder(Serializer, validator, UrlEncoder, Algorithm);
decodedPayload = decoder.Decode(token, SecretKey, verify: true);
resultMessage = "Token validation successful";
return true;
}
catch (TokenExpiredException)
{
resultMessage = "Token has expired";
return false;
}
catch (SignatureVerificationException)
{
resultMessage = "Token signature verification failed";
return false;
}
}
public static long GetUnixTimestamp(DateTime dateTime)
{
DateTime utcTime = dateTime.ToUniversalTime();
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return (long)(utcTime - epoch).TotalSeconds;
}
}
}
3. 토큰 생성 및 검증
// 클레임 설정
var claims = new Dictionary<string, object>
{
{ "iss", "YourAppName" },
{ "exp", JwtTokenHelper.GetUnixTimestamp(DateTime.UtcNow.AddHours(2)) },
{ "sub", "auth-token" },
{ "aud", "YourApp" },
{ "iat", DateTime.UtcNow.ToString("o") },
{ "data", new { user = "example", role = "admin" } }
};
string token = JwtTokenHelper.GenerateToken(claims);
string outputPayload;
string message;
bool isValid = JwtTokenHelper.VerifyToken(token, out outputPayload, out message);
4. Swagger에 토큰 헤더 추가
먼저 JavaScript 파일을 생성합니다 (예: token-header-inject.js):
(function () {
$(function () {
$('#input_apiKey').show();
$('#input_apiKey').on('change', function () {
var key = this.value;
if (key && key.trim() !== '') {
swaggerUi.api.clientAuthorizations.add(
"bearer",
new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header")
);
}
});
});
})();
이후 SwaggerConfig.cs 파일에서 아래 설정을 활성화합니다:
c.BasicAuth("basic")
.Description("Basic HTTP Authentication");
c.InjectJavaScript(
thisAssembly,
"YourProject.Scripts.token-header-inject.js"
);
스크립트 경로를 실제 프로젝트 구조에 맞게 수정한 후, Swagger UI에서 Bearer 토큰을 입력하여 API를 테스트할 수 있습니다.