Skip to content

Instantly share code, notes, and snippets.

@Mogikan
Created March 25, 2020 04:22
Show Gist options
  • Save Mogikan/faabbf81caf3389a61a9e0dcadec3e4d to your computer and use it in GitHub Desktop.
Save Mogikan/faabbf81caf3389a61a9e0dcadec3e4d to your computer and use it in GitHub Desktop.
var clientId = nativeCall ? AppId : ServiceId;
var clientSecret = CreateNewToken(clientId);
string formData = string.Join("&",
new string[]
{
$"client_id={clientId}",
$"code={authCode}",
$"client_secret={clientSecret}",
$"grant_type=authorization_code",
$"redirect_uri={WebUtility.UrlEncode(redirectUri)}"
});
//Exchange code for access token
var tokenUri = new System.Uri(OAuthTokenURL);
//Fiddler
//tokenRequest.Proxy = new WebProxy("127.0.0.1", 8888);
var exchangeWC = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
exchangeWC.Headers.Add(HttpRequestHeader.UserAgent, "whateveryouwant");
exchangeWC.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var appleTokenResponseString = exchangeWC.UploadString(tokenUri, formData);
var responseJSON = JObject.Parse(appleTokenResponseString);
var id_token = responseJSON.GetValue("id_token").ToString();
var handler = new JwtSecurityTokenHandler();
var jwt = handler.ReadJwtToken(id_token);
var userId = jwt.Claims.FirstOrDefault((c) => c.Type == "sub").Value;
var email = jwt.Claims.FirstOrDefault((c) => c.Type == "email")?.Value;
...
private string CreateNewToken(string clientId)
{
//https://www.scottbrady91.com/OpenID-Connect/Implementing-Sign-In-with-Apple-in-ASPNET-Core
const string iss = TeamId; // issuer, your account's team ID found in the dev portal
const string aud = AppleAudience;//The audience registered claim key, the value of which identifies the recipient the JWT is intended for. In our case this token is meant for Apple
string sub = clientId; // same as client_id
Logger.Instance.Info($"iss:{TeamId} aud:{AppleAudience} sub:{clientId}");
// contents of .p8 file
const string privateKey = "your keyhere+";
var cngKey = CngKey.Import(
Convert.FromBase64String(privateKey),
CngKeyBlobFormat.Pkcs8PrivateBlob);
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateJwtSecurityToken(
issuer: iss,
audience: aud,
subject: new ClaimsIdentity(new List<Claim> { new Claim("sub", sub) }),
expires: DateTime.UtcNow.AddDays(2), // expiry can be a maximum of 6 months
issuedAt: DateTime.UtcNow.AddDays(-1),
notBefore: DateTime.UtcNow.AddDays(-1),
signingCredentials: new SigningCredentials(
new ECDsaSecurityKey(new ECDsaCng(cngKey)), SecurityAlgorithms.EcdsaSha256));
return handler.WriteToken(token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment