public ActionResult JwksDocument() { return(Content(JsonConvert.SerializeObject(new JwksModel { Keys = new[] { JwksKeyModel.FromSigningCredentials(SigningCredentials.Value) } }), "application/json")); }
public ActionResult JwksDocument() { string host = configuration.GetSection("JWTSettings")["HostEnvironment"]; SigningCertThumbprint = configuration.GetSection("JWTSettings")["SigningCertThumbprint"]; //One way to handle Windows-based certs if (host.ToLower() == "windows") { SigningCredentials = new Lazy <X509SigningCredentials>(() => { X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = certStore.Certificates.Find( X509FindType.FindByThumbprint, SigningCertThumbprint, false); // Get the first cert with the thumbprint if (certCollection.Count > 0) { return(new X509SigningCredentials(certCollection[0])); } throw new Exception("Certificate not found"); }); } //And another way to handle Linux certs if (host.ToLower() == "linux") { var bytes = System.IO.File.ReadAllBytes($"/var/ssl/private/{SigningCertThumbprint}.p12"); var cert = new X509Certificate2(bytes); SigningCredentials = new Lazy <X509SigningCredentials>(() => { if (cert != null) { return(new X509SigningCredentials(cert)); } throw new Exception("Certificate not found"); }); } return(Content(JsonConvert.SerializeObject(new JWKSModel { Keys = new[] { JwksKeyModel.FromSigningCredentials(SigningCredentials.Value) } }), "application/json")); }
public string BuildSerializedJwks() { var certificate = _vaultCryptoValues.Value.SigningCredentials.Certificate; // JWK cert data must be base64 (not base64url) encoded string certData = Convert.ToBase64String(certificate.Export(X509ContentType.Cert)); // JWK thumbprints must be base64url encoded (no padding or special chars) string thumbprint = Base64UrlEncoder.Encode(certificate.GetCertHash()); // JWK must have the modulus and exponent explicitly defined RSA rsa = certificate.GetRSAPublicKey(); if (rsa == null) { throw new InvalidOperationException("Certificate is not an RSA certificate."); } var keyParams = rsa.ExportParameters(false); var keyModulus = Base64UrlEncoder.Encode(keyParams.Modulus); var keyExponent = Base64UrlEncoder.Encode(keyParams.Exponent); var keyModel = new JwksKeyModel { Kid = _vaultCryptoValues.Value.SigningCredentials.Kid, Kty = "RSA", Nbf = new DateTimeOffset(certificate.NotBefore).ToUnixTimeSeconds(), Use = "sig", Alg = _vaultCryptoValues.Value.SigningCredentials.Algorithm, X5C = new[] { certData }, X5T = thumbprint, N = keyModulus, E = keyExponent }; var result = new JwksModel { Keys = new[] { keyModel } }; var serializedResult = JsonConvert.SerializeObject(result); return(serializedResult); }