example.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} |