초기커밋

This commit is contained in:
2025-05-01 07:20:41 +09:00
commit 98bb2e3c5c
2747 changed files with 646947 additions and 0 deletions

View File

@@ -0,0 +1,92 @@

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using ServerCore; using ServerBase;
namespace BrokerCore.Services;
using Common;
public class JwtGenerator
{
private readonly JwtOption m_jwt_option;
public JwtGenerator(JwtOption jwtOption)
{
m_jwt_option = jwtOption;
}
public JwtOption JwtOption => m_jwt_option;
// Access Token 생성
public string generateAccessToken(string planetId, string planetServerType, string? refreshToken = null)
{
// todo: 토큰 유효기간 설정
var issued_at = new DateTime(2025, 3, 1, 0, 0, 0, DateTimeKind.Utc);
var expires = issued_at.AddYears(1);
var security_key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(m_jwt_option.Secret));
var credentials = new SigningCredentials(security_key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sid, planetId), // 사용자 ID
new Claim(JwtRegisteredClaimNames.Typ, planetServerType),
};
var header = new JwtHeader(credentials);
var payload = new JwtPayload(
issuer:null,
audience:null,
claims: claims,
notBefore: null, // 토큰이 유효 일시
expires: expires, // 토큰 만료 일시
issuedAt: issued_at // iat 발행일시
);
var token = new JwtSecurityToken(header, payload);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
public class JwtParser
{
private readonly JwtOption m_jwt_option;
public JwtParser(JwtOption jwtOption)
{
m_jwt_option = jwtOption;
}
public ClaimsPrincipal? parseToken(string token)
{
var token_handler = new JwtSecurityTokenHandler();
// 시크릿 키를 바이트 배열로 변환
var key = Encoding.UTF8.GetBytes(m_jwt_option.Secret);
// 토큰 검증 매개변수 설정
var validation_parameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidIssuer = "",
ValidAudience = "",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
try
{
// 토큰 검증 및 클레임 추출
var principal = token_handler.ValidateToken(token, validation_parameters, out var validated_token);
return principal;
}
catch (SecurityTokenException ex)
{
Log.getLogger().error($"JWT 파싱 에러 => {ex.Message}");
}
return null;
}
}