Microsoft MVP성태의 닷넷 이야기
닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석 [링크 복사], [링크+제목 복사],
조회: 2152
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  73  74  [75]  ...
NoWriterDateCnt.TitleFile(s)
11788정성태12/4/201810913오류 유형: 506. SqlClient - Value was either too large or too small for an Int32.Couldn't store <2151292191> in ... Column
11787정성태11/29/201814982Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models파일 다운로드1
11786정성태11/29/201811569오류 유형: 505. OpenGL.NET 예제 실행 시 "Managed Debugging Assistant 'CallbackOnCollectedDelegate'" 예외 발생
11785정성태11/21/201814024디버깅 기술: 120. windbg 분석 사례 - ODP.NET 사용 시 Finalizer에서 System.AccessViolationException 예외 발생으로 인한 비정상 종료
11784정성태11/18/201813699Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices파일 다운로드1
11783정성태11/18/201811792오류 유형: 504. 윈도우 환경에서 docker가 설치된 컴퓨터 간의 ping IP 주소 풀이 오류
11782정성태11/18/201811564Windows: 152. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선순위 조정 기능 - 두 번째 이야기
11781정성태11/17/201813781개발 환경 구성: 422. SFML.NET 라이브러리 설정 방법 [1]파일 다운로드1
11780정성태11/17/201815307오류 유형: 503. vcpkg install bzip2 빌드 에러 - "Error: Building package bzip2:x86-windows failed with: BUILD_FAILED"
11779정성태11/17/201815759개발 환경 구성: 421. vcpkg 업데이트 [1]
11778정성태11/14/201813480.NET Framework: 803. UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결
11777정성태11/13/201812449오류 유형: 502. Your project does not reference "..." framework. Add a reference to "..." in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
11776정성태11/13/201811802.NET Framework: 802. Windows에 로그인한 계정이 마이크로소프트의 계정인지, 로컬 계정인지 알아내는 방법
11775정성태11/13/201814270Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing파일 다운로드1
11774정성태11/8/201812129Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader파일 다운로드1
11773정성태11/7/201811842Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer파일 다운로드1
11772정성태11/6/201814198Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO파일 다운로드1
11771정성태11/5/201813245사물인터넷: 56. Audio Jack 커넥터의 IR 적외선 송신기 - 두 번째 이야기 [1]
11770정성태11/5/201820518Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [3]파일 다운로드1
11769정성태11/5/201812172오류 유형: 501. 프로젝트 msbuild Publish 후 connectionStrings의 문자열이 $(ReplacableToken_...)로 바뀌는 문제
11768정성태11/2/201812139.NET Framework: 801. SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
11767정성태11/1/201813511사물인터넷: 55. New NodeMcu v3(ESP8266)의 IR LED (적외선 송신) 제어파일 다운로드1
11766정성태10/31/201815024사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
11765정성태10/26/201812522개발 환경 구성: 420. Visual Studio Code - Arduino Board Manager를 이용한 사용자 정의 보드 선택
11764정성태10/26/201816265개발 환경 구성: 419. MIT 라이선스로 무료 공개된 Detours API 후킹 라이브러리 [2]
11763정성태10/25/201814108사물인터넷: 53. New NodeMcu v3(ESP8266)의 https 통신
... 61  62  63  64  65  66  67  68  69  70  71  72  73  74  [75]  ...