Microsoft MVP성태의 닷넷 이야기
닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석 [링크 복사], [링크+제목 복사],
조회: 2146
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 9개 있습니다.)
.NET Framework: 351. JavaScriptSerializer, DataContractJsonSerializer, Json.NET
; https://www.sysnet.pe.kr/2/0/1391

.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/11224

.NET Framework: 756. JSON의 escape sequence 문자 처리 방식
; https://www.sysnet.pe.kr/2/0/11532

사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
; https://www.sysnet.pe.kr/2/0/11766

.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen
; https://www.sysnet.pe.kr/2/0/12688

.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json
; https://www.sysnet.pe.kr/2/0/13214

.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
; https://www.sysnet.pe.kr/2/0/13342

닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석
; https://www.sysnet.pe.kr/2/0/13623

닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리
; https://www.sysnet.pe.kr/2/0/13644




C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석

지난 글에서,

C# - Google 로그인 연동 (ASP.NET 예제)
; https://www.sysnet.pe.kr/2/0/13622

기왕에 구글 OAuth로부터 JWT를 구했으니, 재미 삼아 해당 정보를 GoogleJsonWebSignature.ValidateAsync 메서드에 의존하지 않고 파싱을 해보겠습니다.

우선, ExchangeCodeForTokenAsync 메서드가 반환한 IdToken이 담고 있는 JWT 값은 "." 문자를 기준으로 3개의 base64 문자열 구획으로 나뉩니다.

eyJhbGciOi---[생략]---iOiJKV1QifQ.eyJpc3MiO---[생략]---MTU1NTI5fQ.Dmd_yu---[생략]---IvYsCg

첫 번째와 두 번째를 base64 디코딩하면 각각 이런 결과가 나옵니다. (보기 좋게 들여 쓰기를 했을 뿐 실제로는 한 줄입니다.)

// JWT Header

{
    "alg":"RS256",
    "kid":"ac3e3e558111c7c7a75c5b65134d22f63ee006d0",
    "typ":"JWT"
}

// JWT data

{
    "iss":"https://accounts.google.com",
    "azp":"...client_id...",
    "aud":"...client_id...",
    "sub":"...user_subject...",
    "email":"...",
    "email_verified":true,
    "at_hash":"Vof-...[생략]..._kQ",
    "iat":1715151929,
    "exp":1715155529
}

세 번째의 경우에는 signature로 첫 번째 디코딩의 "alg"에 지정한 서명 알고리즘을 사용해 JWT의 header 및 data가 위/변조되지 않았음을 확인하는 용도입니다.




자, 그럼 이것을 C# 코드로 확인해 볼까요? ^^ 이에 대해서는 다음의 글에서 대충 뼈대를 가져올 수 있습니다.

Verifying JWT signed with the RS256 algorithm using public key in C#
; https://stackoverflow.com/questions/34403823/verifying-jwt-signed-with-the-rs256-algorithm-using-public-key-in-c-sharp

시작은 우선, 3개의 dot으로 문자열을 나누고 헤더 먼저 Base64 decode를 하면 될 듯한데,

string text = File.ReadAllText(@"C:\temp\jwt_sample.txt");
string[] tokens = text.Split('.');

byte [] header = Convert.FromBase64String(tokens[0]); // 예외 발생

의외로 이런 오류가 발생합니다.

System.FormatException: 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.'


이에 대해 검색해 보면 JWT는 평범한 Base64가 아닌 Base64Url 인코딩을 한 거라고 합니다. ^^;

base64url encoding
; https://brockallen.com/2014/10/17/base64url-encoding/

그래서 위의 글에서 공개한 소스코드로, (또는 ASP.NET Core의 경우 WebEncoders, 또는 Base64UrlTextEncoder를 이용해,)

// 또는, ASP.NET인 경우 HttpServerUtility.UrlTokenEncode를 이용하거나,
// 또는, Katana의 Microsoft.Owin.Security 어셈블리에서 제공하는 Base64UrlTextEncoder를 이용
public static class Base64Url
{
    public static string Encode(byte[] arg)
    {
        string s = Convert.ToBase64String(arg); // Standard base64 encoder
            
        s = s.Split('=')[0]; // Remove any trailing '='s
        s = s.Replace('+', '-'); // 62nd char of encoding
        s = s.Replace('/', '_'); // 63rd char of encoding
            
        return s;
    }

    public static byte[] Decode(string arg)
    {
        string s = arg;
        s = s.Replace('-', '+'); // 62nd char of encoding
        s = s.Replace('_', '/'); // 63rd char of encoding
            
        switch (s.Length % 4) // Pad with trailing '='s
        {
            case 0: break; // No pad chars in this case
            case 2: s += "=="; break; // Two pad chars
            case 3: s += "="; break; // One pad char
            default: throw new Exception("Illegal base64url string!");
        }
            
        return Convert.FromBase64String(s); // Standard base64 decoder
    }
}

다음과 같이 처리할 수 있습니다.

string text = File.ReadAllText(@"C:\temp\test.txt");
string[] tokens = text.Split('.');

byte [] header = Base64Url.Decode(tokens[0]);
JwtHeader jwtHeader = JwtHeader.Parse(header);

public struct JwtHeader
{
    public string alg { get; set; } = "";
    public string kid { get; set; } = "";
    public string typ { get; set; } = "";

    public JwtHeader() { }

    public static JwtHeader Parse(byte[] header)
    {
        return JsonSerializer.Deserialize<JwtHeader>(header);
    }
}

같은 방식으로 두 번째 파트인 JWT data 영역도 구합니다.

byte[] data = Base64Url.Decode(tokens[1]);
JwtData jwtData = JwtData.Parse(data);

// https://developers.google.com/identity/openid-connect/openid-connect?hl=ko#an-id-tokens-payload
public struct JwtData
{
    public string iss { get; set; } = "";
    public string azp { get; set; } = "";
    public string aud { get; set; } = "";
    public string sub { get; set; } = "";
    public string email { get; set; } = "";
    public bool email_verified { get; set; }
    public string at_hash { get; set; }
    public string name { get; set; } = "";
    public string picture { get; set; } = "";
    public string given_name { get; set; } = "";
    public int iat { get; set; }
    public int exp { get; set; }

    public JwtData() { }

    public static JwtData Parse(byte[] data)
    {
        return JsonSerializer.Deserialize<JwtData>(data);
    }
}

마지막으로 세 번째 파트인데요, 여기 담겨 있는 값은 구글 측에서 앞선 2개의 파트를 자신들이 소유한 개인키로 서명한 해시값에 불과합니다. 따라서, 위/변조를 걱정하지 않는다면 그냥 생략하고 넘어가도 됩니다. 하지만, 이것은 비밀번호를 평문으로 데이터베이스에 저장하는 것과 유사한 보안 결함을 가질 수 있으므로 특별한 이유가 없다면 꼭 체크하는 것이 권장됩니다.

그렇다면 이제 필요한 것은 구글이 서명에 사용한 개인키에 대한 공개키를 구해야 합니다. 위의 JWT 구조를 보면 아시겠지만 이 값은 payload에 포함돼 있지 않습니다.

대신, JWT data의 iss 필드에 기록된,

{
    "iss":"https://accounts.google.com",
    "azp":"...client_id...",
    ...[생략]...
    "exp":1715155529
}

경로에서 ".well-known/openid-configuration" 상대 경로를 덧붙여 접근할 수 있는 데이터에서 공개키 정보를 갖는 경로를 구할 수 있습니다. 그래서 다음과 같이 HTTP 요청을 보내서,

string iss = $"{payload.iss}/.well-known/openid-configuration";
var httpClient = new HttpClient();
text = await httpClient.GetStringAsync(iss);

받아온 text는 다음과 같은 식이고,

{
 "issuer": "https://accounts.google.com",
 "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth",
 "device_authorization_endpoint": "https://oauth2.googleapis.com/device/code",
 "token_endpoint": "https://oauth2.googleapis.com/token",
 "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo",
 "revocation_endpoint": "https://oauth2.googleapis.com/revoke",
 "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs",
 "response_types_supported": [
  "code",
  "token",
  "id_token",
  "code token",
  "code id_token",
  "token id_token",
  "code token id_token",
  "none"
 ],
 ...[생략]...
}

바로 저 "jwks_uri" 필드가 담고 있는 "https://www.googleapis.com/oauth2/v3/certs" 경로로 공개키를 조회해 올 수 있습니다.

OpenIdConfig idConfig = OpenIdConfig.Parse(text);
text = await httpClient.GetStringAsync(idConfig.jwks_uri);

public class OpenIdConfig
{
    public string issuer { get; set; } = "";
    public string authorization_endpoint { get; set; } = "";
    public string device_authorization_endpoint { get; set; } = "";
    public string token_endpoint { get; set; } = "";
    public string userinfo_endpoint { get; set; } = "";
    public string revocation_endpoint { get; set; } = "";
    public string jwks_uri { get; set; } = "";

    public string[] response_types_supported { get; set; } = Array.Empty<string>();
    public string[] subject_types_supported { get; set; } = Array.Empty<string>();
    public string[] id_token_signing_alg_values_supported { get; set; } = Array.Empty<string>();
    public string[] scopes_supported { get; set; } = Array.Empty<string>();
    public string[] token_endpoint_auth_methods_supported { get; set; } = Array.Empty<string>();
    public string[] claims_supported { get; set; } = Array.Empty<string>();
    public string[] code_challenge_methods_supported { get; set; } = Array.Empty<string>();
    public string[] grant_types_supported { get; set; } = Array.Empty<string>();

    public OpenIdConfig() { }

    public static OpenIdConfig Parse(string data)
    {
        return Parse(Encoding.UTF8.GetBytes(data));
    }

    public static OpenIdConfig Parse(byte[] data)
    {
        return JsonSerializer.Deserialize<OpenIdConfig>(data);
    }
}

이렇게 받아온 text는 이런 식으로 값이 채워져 있습니다.

{
  "keys": [
    {
      "kid": "ac3e3e558111c7c7a75c5b65134d22f63ee006d0",
      "e": "AQAB",
      "n": "puQJMii881LWwQ_OY2pOZx9RJTtpmUhAn2Z4_zrbQ9WmQqld0ufKesvwIAmuFIswzfOWxv1-ijZWwWrVafZ3MOnoB_UJFgjCPwJyfQiwwNMK80MfEm7mDO0qFlvrmLhhrYZCNFXYKDRibujCPF6wsEKcb3xFwBCH4UFaGmzsO0iJiqD2qay5rqYlucV4-kAIj4A6yrQyXUWWTlYwedbM5XhpuP1WxqO2rjHVLmwECUWqEScdktVhXXQ2CW6zvvyzbuaX3RBkr1w-J2U07vLZF5-RgnNjLv6WUNUwMuh-JbDU3tvmAahnVNyIcPRCnUjMk03kTqbSkZfu6sxWF0qNgw",
      "kty": "RSA",
      "alg": "RS256",
      "use": "sig"
    },
    {
      "e": "AQAB",
      "kid": "a3b762f871cdb3bae0044c649622fc1396eda3e3",
      "n": "uBHF-esPKiNlFaAvpdpejD4vpONW9FL0rgLDg1z8Q-x_CiHCvJCpiSehD41zmDOhzXP_fbMMSGpGL7R3duiz01nK5r_YmRw3RXeB0kcS7Z9H8MN6IJcde9MWbqkMabCDduFgdr6gvH0QbTipLB1qJK_oI_IBfRgjk6G0bGrKz3PniQw5TZ92r0u1LM-1XdBIb3aTYTGDW9KlOsrTTuKq0nj-anW5TXhecuxqSveFM4Hwlw7pw34ydBunFjFWDx4VVJqGNSqWCfcERxOulizIFruZIHJGkgunZnB4DF7mCZOttx2dwT9j7s3GfLJf0xoGumqpOMvecuipfTPeIdAzcQ",
      "alg": "RS256",
      "kty": "RSA",
      "use": "sig"
    }
  ]
}

RSA 키에 대충 아시는 분이라면, "n"이 "Modulus" 값이고, "e"가 "Exponent"임을 감각적으로 추측할 수 있을 것입니다.

그래서 위의 결과는 2개의 공개키를 담고 있는데, 어떤 것을 선택할지는 첫 번째 JWT 헤더에,

{
    "alg":"RS256",
    "kid":"ac3e3e558111c7c7a75c5b65134d22f63ee006d0",
    "typ":"JWT"
}

명시된 key id와 일치하는 걸로 구하면 됩니다. 즉, 위의 결과에서는 첫 번째 공개키에 있는 n과 e 값을 이용해 RSA 타입을 초기화시켜 서명 검증을 할 수 있습니다.

// Verifying JWT signed with the RS256 algorithm using public key in C#
// ; https://stackoverflow.com/questions/34403823/verifying-jwt-signed-with-the-rs256-algorithm-using-public-key-in-c-sharp

GoogleOAuth2Certs certInfo = GoogleOAuth2Certs.Parse(text);

byte[] signature = Base64Url.Decode(tokens[2]);

RSACryptoServiceProvider? rsa = certInfo.Get(jwt.kid);
ArgumentNullException.ThrowIfNull(rsa);

// JWT header와 body를 다시 해시하고,
SHA256 sha256 = SHA256.Create();
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(tokens[0] + '.' + tokens[1])); 

RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
rsaDeformatter.SetHashAlgorithm("SHA256");

// 그 해시한 값과 signature에 담긴 값을 비교해,
bool result = rsaDeformatter.VerifySignature(hash, signature);

Console.WriteLine(result); // result == True가 나와야 위/변조가 되지 않았음을 확신

public class GoogleOAuth2Certs
{
    public JwtPublicKey[] keys { get; set; } = Array.Empty<JwtPublicKey>();

    public RSACryptoServiceProvider? Get(string id)
    {
        foreach (var key in keys)
        {
            if (key.kid == id)
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(
                  new RSAParameters()
                  {
                      Modulus = Base64Url.Decode(key.n),
                      Exponent = Base64Url.Decode(key.e),
                  });

                return rsa;
            }
        }

        return null;
    }

    public GoogleOAuth2Certs() { }

    public static GoogleOAuth2Certs Parse(string data)
    {
        return Parse(Encoding.UTF8.GetBytes(data));
    }

    public static GoogleOAuth2Certs Parse(byte[] data)
    {
        return JsonSerializer.Deserialize<GoogleOAuth2Certs>(data);
    }
}

public struct JwtPublicKey
{
    public string kid { get; set; } = "";
    public string e { get; set; } = "";
    public string n { get; set; } = "";
    public string kty { get; set; } = "";
    public string alg { get; set; } = "";
    public string use { get; set; } = "";

    public JwtPublicKey() { }
}

정상적인 경우라면, RSAPKCS1SignatureDeformatter.VerifySignature 메서드의 반환 결과는 "True"가 나와야 합니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, Visual Studio의 디버깅 중에 필드 값을 확인할 수 있는 Text Visualizer는 JWT 디코딩을 지원하기 때문에,

Debugging Encoded Text
; https://devblogs.microsoft.com/visualstudio/debugging-encoded-text/

지난 ASP.NET 예제를 실행시켰을 때 (JWT 데이터를 담고 있는) IdToken을 아래 화면처럼 직접 디버깅 중에 확인하는 것도 가능합니다.

vs_jwt_parser_1.png




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/11/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11150정성태2/21/201712524.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201715808오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201714570.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201714943오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201713096오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201714332.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201717979.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201715006.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201722314.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201717048.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201713550.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201715638.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201714358VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201713584Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201712937오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201713609Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면?
11134정성태1/20/201720890.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201716633.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201727105.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201717058.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201716940.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201721258.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201717036.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201716060기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201720266기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201717263개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...