public void CanValidateES256()
        {
            const string token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q";
            var          x     = Base64Url.DeserializeBytes("f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", "ECDSA key X value");
            var          y     = Base64Url.DeserializeBytes("x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", "ECDSA key Y value");

            var key = new ECDsaSecurityKey(ECDsa.Create(new ECParameters
            {
                Q = new ECPoint
                {
                    X = x,
                    Y = y
                },
                Curve = ECCurve.NamedCurves.nistP384
            }));

            IdentityModelEventSource.ShowPII = true;

            var result = new JsonWebTokenHandler().ValidateToken(token, new TokenValidationParameters
            {
                IssuerSigningKey = key,
                ClockSkew        = TimeSpan.FromDays(4000),
                ValidIssuer      = "joe",
                ValidateAudience = false
            });

            result.IsValid.ShouldBeTrue();
        }
        private ClaimsPrincipal ValidateSignature(string identityToken, JwtSecurityTokenHandler handler, TokenValidationParameters parameters)
        {
            if (parameters.RequireSignedTokens)
            {
                // read keys from provider information
                var keys = new List <SecurityKey>();

                foreach (var webKey in _options.ProviderInformation.KeySet.Keys)
                {
                    if (webKey.E.IsPresent() && webKey.N.IsPresent())
                    {
                        // only add keys used for signatures
                        if (webKey.Use == "sig" || webKey.Use == null)
                        {
                            var e = Base64Url.Decode(webKey.E);
                            var n = Base64Url.Decode(webKey.N);

                            var key = new RsaSecurityKey(new RSAParameters {
                                Exponent = e, Modulus = n
                            });
                            key.KeyId = webKey.Kid;

                            keys.Add(key);

                            _logger.LogDebug("Added signing key with kid: {kid}", key?.KeyId ?? "not set");
                        }
                    }
                    else if (webKey.X.IsPresent() && webKey.Y.IsPresent() && webKey.Crv.IsPresent())
                    {
#if NETSTANDARD2_0
                        var ec = ECDsa.Create(new ECParameters
                        {
                            Curve = GetCurveFromCrvValue(webKey.Crv),
                            Q     = new ECPoint
                            {
                                X = Base64Url.Decode(webKey.X),
                                Y = Base64Url.Decode(webKey.Y)
                            }
                        });

                        var key = new ECDsaSecurityKey(ec);
                        key.KeyId = webKey.Kid;

                        keys.Add(key);
#else
                        _logger.LogDebug("Found an EC key with kid: {kid}, but .NET Framework 4.6.1 does not support that.", webKey.Kid ?? "not set");
#endif
                    }
                    else
                    {
                        _logger.LogDebug("Signing key with kid: {kid} currently not supported", webKey.Kid ?? "not set");
                    }
                }

                parameters.IssuerSigningKeys = keys;
            }

            SecurityToken token;
            return(handler.ValidateToken(identityToken, parameters, out token));
        }
        public static string GenerateAppleToken(string secret, string keyId, string sub, string iss, string aud, DateTime expires)
        {
            ReadOnlySpan <byte> keyAsSpan = Convert.FromBase64String(secret);
            var prvKey = ECDsa.Create();

            prvKey.ImportPkcs8PrivateKey(keyAsSpan, out var read);
            IJwtAlgorithm algorithm = new ES256Algorithm(ECDsa.Create(), prvKey);

            var tokenHandler    = new JwtSecurityTokenHandler();
            var securityKey     = new ECDsaSecurityKey(prvKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Expires            = expires,
                Issuer             = iss,
                Audience           = aud,
                SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256),
                Subject            = new ClaimsIdentity(new[] { new Claim("sub", sub) }),
            };

            var header = new Dictionary <string, object>()
            {
                { "kid", keyId }
            };


            var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);

            token.Header.Add("kid", keyId);
            return(tokenHandler.WriteToken(token));
        }
Exemplo n.º 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddInMemoryIdentityResources(Config.IdentityResources)
                          .AddInMemoryApiResources(Config.ApiResources)
                          .AddInMemoryApiScopes(Config.ApiScopes)
                          .AddInMemoryClients(Config.Clients)
                          .AddTestUsers(TestUsers.Users);

            var pemBytes = Convert.FromBase64String(
                @"MHcCAQEEIB2EbKgBGbRxWTtWheDgaNw3P7TsSsMoWloU4NHO3MWYoAoGCCqGSM49
AwEHoUQDQgAEVGVVEnzMZnTv/8Jk0/WlFs9poYA7XqI7ITHH78OPenhGS02GBjXM
WV/akdaWBgIyUP8/86kJ2KRyuHR4c/jIuA==");

            var ecdsa = ECDsa.Create();

            ecdsa.ImportECPrivateKey(pemBytes, out _);
            var securityKey = new ECDsaSecurityKey(ecdsa)
            {
                KeyId = "ef208a01ef43406f833b267023766550"
            };

            builder.AddSigningCredential(securityKey, IdentityServerConstants.ECDsaSigningAlgorithm.ES256);
            builder.AddSigningCredential(new RsaSecurityKey(RSA.Create()), IdentityServerConstants.RsaSigningAlgorithm.RS256);
        }
Exemplo n.º 5
0
        private async Task <string> GenerateJwtMobileToken(DeliveryAccount account)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, account.MobileUserId),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, account.Id),
                new Claim(CustomClaimType.CourtId, account.CourtId.ToString()),
                new Claim(CustomClaimType.LawUnitId, account.LawUnitId.ToString()),
            };

            // var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtMobileKey"]));
            //  var creds = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256); // .EcdsaSha512); // HmacSha256);
            string privateKey = configuration["JwtMobileKey"];
            ECDsa  eCDsa      = EDCsaHelper.LoadPrivateKey(EDCsaHelper.FromHexString(privateKey));
            var    key        = new ECDsaSecurityKey(eCDsa);
            var    creds      = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha512); // .EcdsaSha512); // HmacSha256);
            var    expires    = DateTime.Now.AddDays(Convert.ToDouble(configuration["JwtMobileExpireDays"]));

            var token = new JwtSecurityToken(
                configuration["JwtMobileIssuer"],
                configuration["JwtMobileIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create a new client secret (per request).
        /// </summary>
        /// <param name="issuer">Your account's team ID found in the dev portal.</param>
        /// <param name="audience">Apple authority.</param>
        /// <param name="subject">The service id (client_id).</param>
        /// <param name="privateKey">Base64 encoded private key.</param>
        /// <param name="privateKeyId">The key id.</param>
        /// <param name="duration">Expiry can be a maximum of 6 months - generate one per request or re-use until expiration. Defaults to 5 minutes.</param>
        public static string CreateNewToken(string issuer, string audience, string subject, string privateKey, string privateKeyId, TimeSpan?duration = null)
        {
            duration ??= TimeSpan.FromMinutes(5);
            var now   = DateTime.UtcNow;
            var ecdsa = ECDsa.Create();

            if (privateKey.StartsWith('-'))
            {
                var lines = privateKey.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                privateKey = string.Join("", lines.Skip(1).Take(lines.Length - 2));
            }
//#if NETCOREAPP3_1
            ecdsa?.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKey), out _);
//#else
            //ecdsa?.ImportFromPem(privateKey);
//#endif
            var handler = new JsonWebTokenHandler();
            var key     = new ECDsaSecurityKey(ecdsa)
            {
                KeyId = privateKeyId
            };

            return(handler.CreateToken(new SecurityTokenDescriptor {
                Issuer = issuer,
                Audience = audience,
                Claims = new Dictionary <string, object> {
                    { "sub", subject }
                },
                Expires = now.Add(duration.Value),
                IssuedAt = now,
                NotBefore = now,
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256)
            }));
        }
        public async Task <SecurityKeyWithAlgorithm> GetSigningSecurityKey()
        {
            var secret = await _outbackDbContext.Secrets.SingleOrDefaultAsync(m => m.ActiveSigningKey == true);

            switch (secret.PublicKeyCryptographyType)
            {
            case PublicKeyCryptographyType.EC_NistP256:
                var storedParameters = JsonSerializer.Deserialize <CryptographyParameters>(secret.CryptographyData);
                var ecParameters     = new ECParameters
                {
                    Curve = ECCurve.NamedCurves.nistP256,
                    D     = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedD),
                    Q     = new ECPoint
                    {
                        X = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedX),
                        Y = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedY)
                    }
                };

                var ecdsa = ECDsa.Create();
                ecdsa.ImportParameters(ecParameters);

                var ecdSaKey = new ECDsaSecurityKey(ecdsa)
                {
                    KeyId = storedParameters.KeyId
                };

                return(new SecurityKeyWithAlgorithm(JsonWebKeyConverter.ConvertFromECDsaSecurityKey(ecdSaKey), SecurityAlgorithms.EcdsaSha256));

            default:
                throw new Exception($"{secret.PublicKeyCryptographyType} is not supported");
            }
        }
Exemplo n.º 8
0
        public static GeneratedJwtKey Create()
        {
            Guid   subjectId  = Guid.NewGuid();
            string subjectStr = subjectId.ToString("D");

            ECDsa dsa = ECDsa.Create();

            dsa.GenerateKey(ECCurve.NamedCurves.nistP384);
            ECDsaSecurityKey   secKey       = new ECDsaSecurityKey(dsa);
            SigningCredentials signingCreds = new SigningCredentials(secKey, SecurityAlgorithms.EcdsaSha384);
            JwtHeader          newHeader    = new JwtHeader(signingCreds, null, JwtConstants.HeaderType);

            Claim      audClaim   = new Claim(AuthConstants.ClaimAudienceStr, AuthConstants.ApiKeyJwtAudience);
            Claim      issClaim   = new Claim(AuthConstants.ClaimIssuerStr, AuthConstants.ApiKeyJwtInternalIssuer);
            Claim      subClaim   = new Claim(AuthConstants.ClaimSubjectStr, subjectStr);
            JwtPayload newPayload = new JwtPayload(new Claim[] { audClaim, issClaim, subClaim });

            JwtSecurityToken newToken = new JwtSecurityToken(newHeader, newPayload);

            ECDsa            pubDsa        = ECDsa.Create(dsa.ExportParameters(includePrivateParameters: false));
            ECDsaSecurityKey pubSecKey     = new ECDsaSecurityKey(pubDsa);
            JsonWebKey       jwk           = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(pubSecKey);
            string           publicKeyJson = JsonSerializer.Serialize(jwk, new JsonSerializerOptions()
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
            });
            string publicKeyEncoded = Base64UrlEncoder.Encode(publicKeyJson);

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string output = tokenHandler.WriteToken(newToken);

            return(new GeneratedJwtKey(output, subjectStr, publicKeyEncoded));
        }
#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
        public void IsSupportedAlgorithm(ECDsaSecurityKey key, string alg, bool expectedResult)
        {
            if (key.CryptoProviderFactory.IsSupportedAlgorithm(alg, key) != expectedResult)
            {
                Assert.True(false, string.Format("{0} failed with alg: {1}. ExpectedResult: {2}", key, alg, expectedResult));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Constructor for X509KeyContainer.
        /// </summary>
        public X509KeyContainer(ECDsaSecurityKey key, string algorithm, DateTime created, TimeSpan certAge, string issuer = "OP")
            : base(key.KeyId, algorithm, created)
        {
            HasX509Certificate = true;

            var distinguishedName = new X500DistinguishedName($"CN={issuer}");

            //var ec = ECDsa.Create(key.ECDsa.par)
            var request = new CertificateRequest(distinguishedName, key.ECDsa, HashAlgorithmName.SHA256);

            request.CertificateExtensions.Add(
                new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));

            request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(
                    new OidCollection {
                new Oid(ServerAuthenticationOid)
            }, false));

            _cert = request.CreateSelfSigned(
                new DateTimeOffset(created, TimeSpan.Zero),
                new DateTimeOffset(created.Add(certAge), TimeSpan.Zero));

            CertificateRawData = Convert.ToBase64String(_cert.Export(X509ContentType.Pfx));
        }
Exemplo n.º 11
0
        public static SecurityKey LoadECDSACert(string serializedParamsPath)
        {
            if (string.IsNullOrEmpty(serializedParamsPath))
            {
                throw new NullReferenceException("Path may not be null or empty");
            }
            var ecDsa = ECDsa.Create();

            if (ecDsa == null)
            {
                throw new InvalidOperationException();
            }

            if (!File.Exists(serializedParamsPath))
            {
                File.WriteAllText(serializedParamsPath, JsonConvert.SerializeObject(ecDsa.ExportParameters(true).ToEcParamsDto()));
                return(new ECDsaSecurityKey(ecDsa));
            }

            var ecParams = JsonConvert.DeserializeObject <EcParamsDto>(File.ReadAllText(serializedParamsPath));

            ecDsa.ImportParameters(ecParams.ToEcParameters());
            var key = new ECDsaSecurityKey(ecDsa)
            {
                CryptoProviderFactory = CryptoProviderFactory.Default
            };

            return(key);
        }
Exemplo n.º 12
0
        private byte[] Sign(byte[] payload, byte[] publicKey, byte[] privateKey)
        {
            var key      = new ECDsaSecurityKey(LoadPrivateKey(privateKey));
            var provider = new AsymmetricSignatureProvider(key, SecurityAlgorithms.EcdsaSha256Signature);

            return(provider.Sign(payload));
        }
Exemplo n.º 13
0
        private bool Verify(byte[] payload, byte[] signature, byte[] publicKey)
        {
            var key      = new ECDsaSecurityKey(LoadPublicKey(publicKey));
            var provider = new AsymmetricSignatureProvider(key, SecurityAlgorithms.EcdsaSha256Signature);

            return(provider.Verify(payload, signature));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Constructor for EcKeyContainer.
        /// </summary>
        public EcKeyContainer(ECDsaSecurityKey key, string algorithm, DateTime created)
            : base(key.KeyId, algorithm, created)
        {
            var parameters = key.ECDsa.ExportParameters(includePrivateParameters: true);

            D = parameters.D;
            Q = parameters.Q;
        }
        public void Constructor()
        {
            // testing constructor that takes ECDsa instance
            ECDsaSecurityKeyConstructorWithEcdsa(null, ExpectedException.ArgumentNullException("ecdsa"));
            ECDsaSecurityKeyConstructorWithEcdsa(new ECDsaCng(), ExpectedException.NoExceptionExpected);
            var ecdsaSecurityKey = new ECDsaSecurityKey(new ECDsaCng());

            Assert.True(ecdsaSecurityKey.HasPrivateKey, "ecdsaSecurityKey.HasPrivate is false");
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get the private ECDSA key from a certificate and set the KeyID
        ///
        /// For ECDSA certificates we need to set the KeyID manually according to a comment here
        /// https://github.com/IdentityServer/IdentityServer4/blob/main/src/IdentityServer4/host/Startup.cs
        /// (directly using the certificate is not support by Microsoft right now)
        ///
        /// So we set the KeyID to something that is consistent and tied to the key,
        /// the first part of the thumbprint is a good starting point.
        /// </summary>
        /// <param name="ecCert"></param>
        /// <returns></returns>
        private static ECDsaSecurityKey GetECDsaPrivateKey(X509Certificate2 ecCert)
        {
            var privateKey = new ECDsaSecurityKey(ecCert.GetECDsaPrivateKey())
            {
                KeyId = ecCert.Thumbprint.Substring(0, 16)
            };

            return(privateKey);
        }
Exemplo n.º 17
0
        private SigningCredentials CreateSigningCredentials(string keyId, ECDsa algorithm)
        {
            var key = new ECDsaSecurityKey(algorithm)
            {
                KeyId = keyId
            };

            return(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256Signature));
        }
        public void Constructor()
        {
            // testing constructor that takes ECDsa instance
            ECDsaSecurityKeyConstructorWithEcdsa(null, ExpectedException.ArgumentNullException("ecdsa"));
            ECDsaSecurityKeyConstructorWithEcdsa(new ECDsaCng(), ExpectedException.NoExceptionExpected);
            var ecdsaSecurityKey = new ECDsaSecurityKey(new ECDsaCng());

            Assert.True(ecdsaSecurityKey.PrivateKeyStatus == PrivateKeyStatus.Unknown, "ecdsaSecurityKey.FoundPrivateKey is unknown");
        }
Exemplo n.º 19
0
        public void AddSigningCredential_with_invalid_curve_should_throw_exception(string curveOid, string alg)
        {
            IServiceCollection     services = new ServiceCollection();
            IIdentityServerBuilder identityServerBuilder = new IdentityServerBuilder(services);

            var key = new ECDsaSecurityKey(ECDsa.Create(
                                               ECCurve.CreateFromOid(Oid.FromOidValue(curveOid, OidGroup.All))));

            Assert.Throws <InvalidOperationException>(() => identityServerBuilder.AddSigningCredential(key, alg));
        }
Exemplo n.º 20
0
        public void AddSigningCredential_with_valid_curve_should_succeed(string curveOid, string alg)
        {
            IServiceCollection     services = new ServiceCollection();
            IIdentityServerBuilder identityServerBuilder = new IdentityServerBuilder(services);

            var key = new ECDsaSecurityKey(ECDsa.Create(
                                               ECCurve.CreateFromOid(Oid.FromOidValue(curveOid, OidGroup.All))));

            identityServerBuilder.AddSigningCredential(key, alg);
        }
Exemplo n.º 21
0
        private TokenValidationResult ValidateSignature(string identityToken, JsonWebTokenHandler handler, TokenValidationParameters parameters, OidcClientOptions options, ILogger logger)
        {
            if (parameters.RequireSignedTokens)
            {
                // read keys from provider information
                var keys = new List <SecurityKey>();

                foreach (var webKey in options.ProviderInformation.KeySet.Keys)
                {
                    if (webKey.E.IsPresent() && webKey.N.IsPresent())
                    {
                        // only add keys used for signatures
                        if (webKey.Use == "sig" || webKey.Use == null)
                        {
                            var e = Base64Url.Decode(webKey.E);
                            var n = Base64Url.Decode(webKey.N);

                            var key = new RsaSecurityKey(new RSAParameters {
                                Exponent = e, Modulus = n
                            });
                            key.KeyId = webKey.Kid;

                            keys.Add(key);

                            logger.LogDebug("Added signing key with kid: {kid}", key?.KeyId ?? "not set");
                        }
                    }
                    else if (webKey.X.IsPresent() && webKey.Y.IsPresent() && webKey.Crv.IsPresent())
                    {
                        var ec = ECDsa.Create(new ECParameters
                        {
                            Curve = GetCurveFromCrvValue(webKey.Crv),
                            Q     = new ECPoint
                            {
                                X = Base64Url.Decode(webKey.X),
                                Y = Base64Url.Decode(webKey.Y)
                            }
                        });

                        var key = new ECDsaSecurityKey(ec);
                        key.KeyId = webKey.Kid;

                        keys.Add(key);
                    }
                    else
                    {
                        logger.LogDebug("Signing key with kid: {kid} currently not supported", webKey.Kid ?? "not set");
                    }
                }

                parameters.IssuerSigningKeys = keys;
            }

            return(handler.ValidateToken(identityToken, parameters));
        }
Exemplo n.º 22
0
        private JsonWebKey CreateJWK()
        {
            var key = new ECDsaSecurityKey(ECDsa.Create(Curve))
            {
                KeyId = Guid.NewGuid().ToString()
            };
            var jwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(key);

            SaveKey(jwk);
            return(jwk);
        }
 private void ECDsaSecurityKeyConstructorWithEcdsa(ECDsa ecdsa, ExpectedException ee)
 {
     try
     {
         var ecdsaSecurityKey = new ECDsaSecurityKey(ecdsa);
         ee.ProcessNoException();
     }
     catch (Exception exception)
     {
         ee.ProcessException(exception);
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Adds an ECDSA-based validation key.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="key">The ECDSA key</param>
        /// <param name="signingAlgorithm">The ECDSA-based signing algorithm</param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddValidationKey(
            this IIdentityServerBuilder builder,
            ECDsaSecurityKey key,
            IdentityServerConstants.ECDsaSigningAlgorithm signingAlgorithm = IdentityServerConstants.ECDsaSigningAlgorithm.ES256)
        {
            var keyInfo = new SecurityKeyInfo
            {
                Key = key,
                SigningAlgorithm = CryptoHelper.GetECDsaSigningAlgorithmValue(signingAlgorithm)
            };

            return(builder.AddValidationKey(keyInfo));
        }
Exemplo n.º 25
0
        internal static bool IsValidCurveForAlgorithm(ECDsaSecurityKey key, string algorithm)
        {
            var parameters = key.ECDsa.ExportParameters(false);

            if (algorithm == SecurityAlgorithms.EcdsaSha256 && parameters.Curve.Oid.Value != CurveOids.P256 ||
                algorithm == SecurityAlgorithms.EcdsaSha384 && parameters.Curve.Oid.Value != CurveOids.P384 ||
                algorithm == SecurityAlgorithms.EcdsaSha512 && parameters.Curve.Oid.Value != CurveOids.P521)
            {
                return(false);
            }

            return(true);
        }
        Task <D2LSecurityToken> IPrivateKeyProvider.GetSigningCredentialsAsync()
        {
            var ecdsa      = ECDsa.Create(m_curve);
            var parameters = ecdsa.ExportParameters(includePrivateParameters: true);

            D2LSecurityToken result = m_d2lSecurityTokenFactory.Create(() => {
                var ecDsa = ECDsa.Create(parameters);
                var key   = new ECDsaSecurityKey(ecDsa);
                return(new Tuple <AsymmetricSecurityKey, IDisposable>(key, ecDsa));
            });

            return(Task.FromResult(result));
        }
Exemplo n.º 27
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var password = "******";
            var ecdsaPFX = @"MIID9wIBAzCCA7MGCSqGSIb3DQEHAaCCA6QEggOgMIIDnDCCAW0GCSqGSIb3DQEHAaCCAV4EggFaMIIBVjCCAVIGCyqGSIb3DQEMCgECoIHMMIHJMBwGCiqGSIb3DQEMAQMwDgQI6Rn/G4nB1SACAgfQBIGoRg/w/KUDAumcM0STBZ
DYefbKsk3M6p7qILoOIfD2k4i9gkL0+JKWbSSPzOoAtKE9FhGbT2WC1Vyt1CjRsRkPqtCpkU/D2rVwq9BKX483+1x+2JqhuhkMU1NAejn5QUqCPmjKPnWfjVXRPGMmYQoIKK+B9uZiPk0k3FlLC/6/JPI51wA1rwGuor99vgaU02fauNcRDv/CCpWCAeSUZAZApY6jRE9Wwi93MXQwEwYJKoZIhvcNAQkVMQYEBAEAAAAwXQYJKwYBBAGCNxEBMVAeTgBNAGkAYwByAG8AcwBvAGYAdAAgAFMAbwBmAHQAdwBhAHIAZQAgAEsAZQB5ACAAUwB0AG8AcgBhAGcAZQAgAFAAcgBvAHYAaQBkAGUAcjCCAicGCSqGSIb3DQEHBqCCAhgwggIUAgEAMIICDQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQMwDgQI6jHZeCkfSu4CAgfQgIIB4Cx+XJ79QcELNweAZH/LWrTR25Im0HJ/SfATqnNcOvfluz3TxuJOrJUy15exisVjKSBynD6Tl4IyIwLSfJoC9N3ydaMcOvcKATdGDEd5nX8zSWNaJGCJXMQAU3M/YHo+vrOOjatOEs65/3qQSrEITcEPVqN6/lfoBPpZh10NIiGuzhXqbSulki45f2Tly43ondBosqX3NzSQzOlAKmgivMeGxL+mMfpe9IkgHfIsJ9uu4x6iaSKiHdeAzHLtINKQzianHEmiusOaz9hrE0F5AO3NUM8nxtLFouQwX0JreXeFsZPriIqZ4b9p6ulEnw6MC0TjZZ9OOj7MGcvvHQeXCufnQL3FpUghzzG7lBx50Ovf9KzL7lG+mLIU8fkJ19bx6izYwVSHZa0CtZg28bF/mqC19Qi6ev/9j0nC9MmsfA25fnKpe7Ob2ddbkXSa8v6whVTY5C/digfrtKeoQay3B1gTZXKdiRH700ejS6FZ1EliMfMfRYczyc6kYsrBez0AlvkaozgqX8wyD4Z1iSjwYSLmOlguvCIuhDV3crltkjODGRHlyckdlWEJNH0PIJBr9qG1jRnA1t/MWdJK9gHTX2VqwHtPZKxikQq6x1h/hFMpU8ZahD1y886JLnBiBqxkIzA7MB8wBwYFKw4DAhoEFMO4ZPmUTPmNn7Xn57uXiyIWyttZBBTlMlP5OzM3CMlqmNdJOPK+iiOEwQICB9A=";

            byte[] ecdsaCertPfxBytes = Convert.FromBase64String(ecdsaPFX);
            var    ecdsaCertificate  = new X509Certificate2(ecdsaCertPfxBytes, password);



            ECDsaSecurityKey ecdsaCertificatePublicKey = new ECDsaSecurityKey(ecdsaCertificate.GetECDsaPrivateKey());


            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;

                // see https://docs.duendesoftware.com/identityserver/v5/basics/resources
                options.EmitStaticAudienceClaim = true;
                options.KeyManagement.Enabled   = false;
            })
                          .AddTestUsers(TestUsers.Users);

            builder.AddInMemoryIdentityResources(Resources.Identity);
            builder.AddInMemoryApiScopes(Resources.ApiScopes);
            builder.AddInMemoryApiResources(Resources.ApiResources);
            builder.AddInMemoryClients(Clients.List);

            // this is only needed for the JAR and JWT samples and adds supports for JWT-based client authentication
            builder.AddJwtBearerClientAuthentication();

            services.AddAuthentication()
            .AddOpenIdConnect("Google", "Sign-in with Google", options =>
            {
                options.SignInScheme   = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.ForwardSignOut = IdentityServerConstants.DefaultCookieAuthenticationScheme;

                options.Authority = "https://accounts.google.com/";
                options.ClientId  = "708778530804-rhu8gc4kged3he14tbmonhmhe7a43hlp.apps.googleusercontent.com";

                options.CallbackPath = "/signin-google";
                options.Scope.Add("email");
            });
            builder.AddSigningCredential(ecdsaCertificatePublicKey, IdentityServerConstants.ECDsaSigningAlgorithm.ES256);
        }
        public void SigningCredentials_AddKey_ThrowsAnExceptionForEcdsaKeyOnUnsupportedPlatforms()
        {
            // Arrange
            var credentials = new List <SigningCredentials>();
            var key         = new ECDsaSecurityKey(Mock.Of <ECDsa>());

            // Act and assert
            var exception = Assert.Throws <PlatformNotSupportedException>(delegate
            {
                credentials.AddKey(key);
            });

            Assert.Equal("ECDSA signing keys are not supported on this platform.", exception.Message);
        }
Exemplo n.º 29
0
        private static SigningCredentials CreateSigningCredentials(string keyId, ECDsa algorithm)
        {
            var key = new ECDsaSecurityKey(algorithm)
            {
                KeyId = keyId
            };

            // Use a custom CryptoProviderFactory so that keys are not cached and then disposed of, see below:
            // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1302
            return(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256Signature)
            {
                CryptoProviderFactory = CryptoProviderFactory,
            });
        }
        internal override D2LSecurityToken ToSecurityToken()
        {
            var token = new D2LSecurityToken(
                id: Id,
                validFrom: DateTimeOffset.UtcNow,
                validTo: ExpiresAt ?? DateTimeOffset.UtcNow + Constants.REMOTE_KEY_MAX_LIFETIME,
                keyFactory: () => {
                var ecdsa = ECDsa.Create(m_parameters);
                var key   = new ECDsaSecurityKey(ecdsa);
                return(new Tuple <AsymmetricSecurityKey, IDisposable>(key, ecdsa));
            }
                );

            return(token);
        }