Пример #1
0
        public async Task <IActionResult> GetJsonWebKeySetAsync()
        {
            JwksDocument jwksDocument = new JwksDocument
            {
                Keys = new List <JwkDocument>()
            };

            List <X509Certificate2> certificates = await _certificateProvider.GetCertificates();

            foreach (X509Certificate2 cert in certificates)
            {
                string oidFriendlyName = cert.PublicKey.Oid.FriendlyName;

                RSA           rsaPublicKey     = cert.GetRSAPublicKey();
                RSAParameters exportParameters = rsaPublicKey.ExportParameters(false);
                string        exponent         = Convert.ToBase64String(exportParameters.Exponent);
                string        modulus          = Convert.ToBase64String(exportParameters.Modulus);

                List <string> chain = ExportChain(cert);

                JwkDocument jwkDocument = new JwkDocument
                {
                    KeyType = oidFriendlyName, PublicKeyUse = "sig", KeyId = cert.Thumbprint, Exponent = exponent, Modulus = modulus, X509Chain = chain
                };

                jwksDocument.Keys.Add(jwkDocument);
            }

            return(Ok(jwksDocument));
        }
        /// <summary>
        /// Generates a token and serialize it to a compact format
        /// </summary>
        /// <param name="principal">The claims principal for the token</param>
        /// <param name="expires">The Expiry time of the token</param>
        /// <returns>A serialized version of the generated JSON Web Token.</returns>
        private async Task <string> GenerateToken(ClaimsPrincipal principal, DateTime?expires = null)
        {
            List <X509Certificate2> certificates = await _certificateProvider.GetCertificates();

            X509Certificate2 certificate = GetLatestCertificateWithRolloverDelay(
                certificates, _generalSettings.JwtSigningCertificateRolloverDelayHours);

            TimeSpan tokenExpiry = new TimeSpan(0, _generalSettings.JwtValidityMinutes, 0);

            if (expires == null)
            {
                expires = DateTime.UtcNow.AddSeconds(tokenExpiry.TotalSeconds);
            }

            JwtSecurityTokenHandler tokenHandler    = new JwtSecurityTokenHandler();
            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(principal.Identity),
                Expires            = expires,
                SigningCredentials = new X509SigningCredentials(certificate)
            };

            SecurityToken token           = tokenHandler.CreateToken(tokenDescriptor);
            string        serializedToken = tokenHandler.WriteToken(token);

            return(serializedToken);
        }