Esempio n. 1
0
        public void AddClientCredentials([NotNull] ClientCredentials credentials, [NotNull] ConfigStore endpointConfigStore)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }
            if (endpointConfigStore == null)
            {
                throw new ArgumentNullException(nameof(endpointConfigStore));
            }

            if (string.IsNullOrWhiteSpace(credentials.Id))
            {
                throw new InvalidOperationException("Id of credentials cannot be empty.");
            }

            if (string.IsNullOrWhiteSpace(credentials.IdentityProvider?.ToString()))
            {
                throw new InvalidOperationException("IdentityProvider of credentials cannot be empty.");
            }

            if (credentials.KeyPairData == null)
            {
                throw new InvalidOperationException("KeyPairData of credentials cannot be empty.");
            }

            if (credentials.Id == "system-client")
            {
                throw new InvalidOperationException("The system client cannot be saved to config store.");
            }

            if (endpointConfigStore._configName != ConfigurationNames.Zero &&
                endpointConfigStore._configName != ConfigurationNames.Local)
            {
                endpointConfigStore.Endpoints.TryGetValue(EndpointNames.Identity, out var currentEndpoint);

                if (currentEndpoint == null)
                {
                    currentEndpoint = credentials.IdentityProvider;
                    endpointConfigStore.SetEndpoint(EndpointNames.Identity, currentEndpoint);
                }

                if (credentials.IdentityProvider != currentEndpoint)
                {
                    throw new InvalidOperationException($"This credentials have been issued by identity provider '{credentials.IdentityProvider}', but the configuration '{_configName}' uses the provider '{currentEndpoint}'.");
                }
            }

            var privatePath = Path.Combine(StorePath, "private");

            var privateKeyPath = Path.Combine(privatePath, $"{credentials.Id}.key");

            if (!_environment.FileSystem.DirectoryExists(privatePath))
            {
                _environment.FileSystem.CreateDirectory(privatePath);
            }


            var keyPairPtr = Marshal.SecureStringToGlobalAllocUnicode(credentials.KeyPairData);

            try
            {
                var keyPair = PrivateKey.ReadString(Marshal.PtrToStringUni(keyPairPtr));
                PrivateKey.WriteFile(privateKeyPath, keyPair,
                                     _environment.FileSystem);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(keyPairPtr);
            }
        }