Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created April 29, 2022 11:55
Show Gist options
  • Save badsyntax/53dd49e6a255992c4329615225cc4093 to your computer and use it in GitHub Desktop.
Save badsyntax/53dd49e6a255992c4329615225cc4093 to your computer and use it in GitHub Desktop.
example dotnet 6 code to sign an apple JWT from p8 certificate file
public class TokenSigningRequest
{
public string AppleTeamId { get; set; }
public string AppleServiceId { get; set; }
public string AppleKeyId { get; set; }
public string P8key { get; set; }
}
[HttpPost]
public async Task<IActionResult> CreateSignedToken([FromBody, BindRequired] TokenSigningRequest requestBody)
{
string audience = "https://appleid.apple.com";
string issuer = requestBody?.AppleTeamId;
string subject = requestBody?.AppleServiceId;
string kid = requestBody?.AppleKeyId;
string p8key = requestBody?.P8key;
IList<Claim> claims = new List<Claim> {
new Claim ("sub", subject)
};
using (ECDsa key = ECDsa.Create())
{
key.ImportPkcs8PrivateKey(Convert.FromBase64String(p8key), out _);
// CngKey cngKey = CngKey.Import(Convert.FromBase64String(p8key), CngKeyBlobFormat.Pkcs8PrivateBlob);
SigningCredentials signingCred = new SigningCredentials(
new ECDsaSecurityKey(key),
SecurityAlgorithms.EcdsaSha256
);
JwtSecurityToken token = new JwtSecurityToken(
issuer,
audience,
claims,
DateTime.Now,
DateTime.Now.AddDays(180),
signingCred
);
token.Header.Add("kid", kid);
token.Header.Remove("typ");
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
string jwt = tokenHandler.WriteToken(token);
return (ActionResult)new OkObjectResult(new
{
token = jwt
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment