Apple Login Refresh Token 발급 샘플(C#)

2023. 7. 4. 16:40C#

using System.Security.Cryptography;
using JWT.Builder;
using JWT.Algorithms;

string auth_code = "authorization code";

var clientSecret = JwtBuilder.Create()
                      .WithAlgorithm(new ES256Algorithm(ECDsa.Create(), GetPrivateKey()))
                      .AddHeader("kid", "key file id")
                      //.AddHeader("alg", "ES256")
                      // 알고림즘을 사용하면 자동으로 헤더가 생성되는 듯
                      .AddClaim("iss", "자신의 팀 id")
                      .AddClaim("lat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                      .AddClaim("exp", DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds())
                      .AddClaim("aud", "https://appleid.apple.com")
                      .AddClaim("sub", "자신의 번들 id")
                      .Encode();
Console.WriteLine(clientSecret);

HttpClient client = new HttpClient();

var url = "https://appleid.apple.com/auth/token";
Dictionary<string, string> value = new()
{
    {"client_id", "com.roundstar.ToonJido" },
    {"client_secret", clientSecret },
    {"code", auth_code },
    {"grant_type", "authorization_code" }
};

var data = new FormUrlEncodedContent(value);

var response = await client.PostAsync(url, data);

try
{
    response.EnsureSuccessStatusCode();
    var result = await response.Content.ReadAsStringAsync();
    Console.WriteLine("success");
    Console.WriteLine("result: " + result);
}
catch(Exception ex)
{
    Console.WriteLine("Something went worng!");
    Console.WriteLine(ex.Message);
}

static ECDsa GetPrivateKey()
{
    var privateKey = "자신의 비공개키";
    ReadOnlySpan<byte> keyAsSpan = Convert.FromBase64String(privateKey);
    var prvKey = ECDsa.Create();
    prvKey.ImportPkcs8PrivateKey(keyAsSpan, out var read);

    return prvKey;
}

 

참고: https://kedric-me.tistory.com/entry/JAVA-%EC%95%A0%ED%94%8C-%EC%97%B0%EB%8F%99%ED%95%B4%EC%A0%9C-%EA%B5%AC%ED%98%84-Sign-Out-of-Apple-ID