Last active
January 12, 2024 22:16
-
-
Save Gorniv/a593037dd79184f952781077fe568ce3 to your computer and use it in GitHub Desktop.
.net create Apple jwt with .p8 cert for linux
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
using System; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Linq; | |
using System.Security.Cryptography; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.IdentityModel.Tokens; | |
namespace My.Api.Controllers | |
{ | |
[Route("api/[controller]")] | |
[ApiController] | |
public class ValuesController : ControllerBase | |
{ | |
// GET api/values | |
[HttpGet] | |
public ActionResult<string> Get() | |
{ | |
return GetToken(); | |
} | |
private string GetToken() | |
{ | |
var dsa = GetECDsa(); | |
return CreateJwt(dsa, "keyId", "teamId"); | |
} | |
private ECDsa GetECDsa() | |
{ | |
using (TextReader reader = System.IO.File.OpenText("AuthKey_xxxxxxx.p8")) | |
{ | |
var ecPrivateKeyParameters = | |
(ECPrivateKeyParameters)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject(); | |
var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded(); | |
var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded(); | |
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned(); | |
// Convert the BouncyCastle key to a Native Key. | |
var msEcp = new ECParameters {Curve = ECCurve.NamedCurves.nistP256, Q = {X = x, Y = y}, D = d}; | |
return ECDsa.Create(msEcp); | |
} | |
} | |
private string CreateJwt(ECDsa key, string keyId, string teamId) | |
{ | |
var securityKey = new ECDsaSecurityKey(key) { KeyId = keyId }; | |
var credentials = new SigningCredentials(securityKey, "ES256"); | |
var descriptor = new SecurityTokenDescriptor | |
{ | |
IssuedAt = DateTime.Now, | |
Issuer = teamId, | |
SigningCredentials = credentials, | |
}; | |
var handler = new JwtSecurityTokenHandler(); | |
var encodedToken = handler.CreateEncodedJwt(descriptor); | |
return encodedToken; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment