public void FromConfig_IncompleteUserCredential()
        {
            IConfiguration            config = BuildConfigurationForCredential(IncompleteUserCredentialConfigContents);
            JsonCredentialParameters  credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => GoogleCredential.FromJsonParameters(credentialParameters));

            Assert.Contains("does not represent a valid user credential", ex.Message);
        }
        public void FromConfig_Untyped()
        {
            IConfiguration            config = BuildConfigurationForCredential(UntypedCredentialConfigContents);
            JsonCredentialParameters  credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => GoogleCredential.FromJsonParameters(credentialParameters));

            Assert.Contains("Unrecognized credential type", ex.Message);
        }
        public void FromConfig_NotAJson()
        {
            IConfiguration config = new ConfigurationBuilder().AddInMemoryCollection(new KeyValuePair <string, string>[]
            {
                new KeyValuePair <string, string>("GoogleCredential", "NotAJson")
            }).Build();

            JsonCredentialParameters credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();
            ArgumentNullException    ex = Assert.Throws <ArgumentNullException>(() => GoogleCredential.FromJsonParameters(credentialParameters));

            Assert.Equal("credentialParameters", ex.ParamName);
        }
        public void FromConfig_ServiceAccountCredential()
        {
            IConfiguration           config = BuildConfigurationForCredential(DummyServiceAccountCredentialConfigContents);
            JsonCredentialParameters credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();
            GoogleCredential         credential           = GoogleCredential.FromJsonParameters(credentialParameters);

            var serviceCred = Assert.IsType <ServiceAccountCredential>(credential.UnderlyingCredential);

            Assert.True(credential.IsCreateScopedRequired);
            Assert.Equal("CLIENT_EMAIL", serviceCred.Id);
            Assert.Equal("PROJECT_ID", serviceCred.ProjectId);
        }
        private GoogleCredential CreateServiceCredentials()
        {
            var parameters = new JsonCredentialParameters
            {
                Type        = JsonCredentialParameters.ServiceAccountCredentialType,
                ClientEmail = "*****@*****.**",
                PrivateKey  = s_samplePrivateKey
            };
            string json   = JsonConvert.SerializeObject(parameters);
            var    stream = new MemoryStream(Encoding.UTF8.GetBytes(json));

            return(GoogleCredential.FromStream(stream));
        }
Beispiel #6
0
        /// <summary>
        /// Authorizes with the json credential parameters.
        /// </summary>
        /// <returns></returns>
        public async Task AuthorizeJsonAsync(JsonCredentialParameters jsonCredentialParameters, CancellationToken token = default)
        {
            if (!jsonCredentialParameters.Type.Equals("service_account", StringComparison.InvariantCultureIgnoreCase) ||
                string.IsNullOrEmpty(jsonCredentialParameters.ClientEmail) ||
                string.IsNullOrEmpty(jsonCredentialParameters.PrivateKey))
            {
                throw new InvalidOperationException("JSON content does not represent valid service account credentials.");
            }

            var accountInitializer = InitializeAccount(jsonCredentialParameters.ClientEmail)
                                     .FromPrivateKey(jsonCredentialParameters.PrivateKey);

            await CreateCredentials(token, accountInitializer);
        }
        /// <summary>Creates a default credential from JSON data.</summary>
        private static EnfonicaCredential CreateDefaultCredentialFromParameters(JsonCredentialParameters credentialParameters)
        {
            switch (credentialParameters.Type)
            {
            case JsonCredentialParameters.ServiceAccountCredentialType:
                return(EnfonicaCredential.FromServiceAccountCredential(
                           CreateServiceAccountCredentialFromParameters(credentialParameters)));

            default:
                throw new InvalidOperationException(
                          String.Format("Error creating credential from JSON. Unrecognized credential type {0}.",
                                        credentialParameters.Type));
            }
        }
        public void FromConfig_UserCredential()
        {
            IConfiguration           config = BuildConfigurationForCredential(DummyUserCredentialConfigContents);
            JsonCredentialParameters credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();
            GoogleCredential         credential           = GoogleCredential.FromJsonParameters(credentialParameters);

            var userCred = Assert.IsType <UserCredential>(credential.UnderlyingCredential);

            Assert.False(credential.IsCreateScopedRequired);
            Assert.Equal("REFRESH_TOKEN", userCred.Token.RefreshToken);
            var flow = (GoogleAuthorizationCodeFlow)userCred.Flow;

            Assert.Equal("CLIENT_ID", flow.ClientSecrets.ClientId);
            Assert.Equal("CLIENT_SECRET", flow.ClientSecrets.ClientSecret);
            Assert.Equal("PROJECT_ID", flow.ProjectId);
            Assert.Equal("QUOTA_PROJECT", userCred.QuotaProject);
        }
        SubscriberClient.ClientCreationSettings GetSettings()
        {
            var json = new JsonCredentialParameters
            {
                Type         = JsonCredentialParameters.ServiceAccountCredentialType,
                ProjectId    = Options.ProjectId,
                PrivateKeyId = Options.PubSubPrivateKeyId ?? Options.PrivateKeyId,
                PrivateKey   = Options.PubSubPrivateKey ?? Options.PrivateKey,
                ClientEmail  = Options.ClientEmail,
                ClientId     = Options.ClientId
            }.ToJson(new JsonSerializerOptions {
                PropertyNamingPolicy = new SnakeCasePropertyNamingPolicy()
            });

            return(new SubscriberClient.ClientCreationSettings(
                       credentials: GoogleCredential.FromJson(json).ToChannelCredentials()
                       ));
        }
        /// <summary>Creates a <see cref="ServiceAccountCredential"/> from JSON data.</summary>
        private static ServiceAccountCredential CreateServiceAccountCredentialFromParameters(
            JsonCredentialParameters credentialParameters)
        {
            if (credentialParameters.Type != JsonCredentialParameters.ServiceAccountCredentialType ||
                string.IsNullOrEmpty(credentialParameters.ClientEmail) ||
                string.IsNullOrEmpty(credentialParameters.PrivateKey))
            {
                throw new InvalidOperationException("JSON data does not represent a valid service account credential.");
            }
            var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
            {
                ProjectId    = credentialParameters.ProjectId,
                QuotaProject = credentialParameters.QuotaProject, // todo: remove
                KeyId        = credentialParameters.PrivateKeyId
            };

            return(new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey)));
        }
        static ServiceAccountCredential ServiceAccountCredential(
            JsonCredentialParameters credentialParameters,
            IEnumerable <string> scopes,
            string?emailToImpersonate)
        {
            // Create a credential initializer with the correct scopes.
            var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
            {
                Scopes = scopes
            };

            // Configure impersonation (if applicable).
            if (!string.IsNullOrEmpty(emailToImpersonate))
            {
                initializer.User = emailToImpersonate;
            }

            // Create a service account credential object using the deserialized private key.
            var credential = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));

            return(credential);
        }
        private ServiceAccountCredential CreateServiceAccountCredential(JsonCredentialParameters credParams)
        {
            var scopes = new List <string>
            {
                DirectoryService.Scope.AdminDirectoryUserReadonly,
                DirectoryService.Scope.AdminDirectoryGroupReadonly,
                DirectoryService.Scope.AdminDirectoryGroupMemberReadonly
            };

            if (credParams.Type != JsonCredentialParameters.ServiceAccountCredentialType ||
                string.IsNullOrEmpty(credParams.ClientEmail) ||
                string.IsNullOrEmpty(credParams.PrivateKey))
            {
                throw new InvalidOperationException("JSON data does not represent a valid service account credential.");
            }

            var initializer = new ServiceAccountCredential.Initializer(credParams.ClientEmail);

            initializer.User   = SettingsService.Instance.Server.GSuite.AdminUser;
            initializer.Scopes = scopes;

            return(new ServiceAccountCredential(initializer.FromPrivateKey(credParams.PrivateKey)));
        }
        public void FromConfig_WrongTypesUserCredential()
        {
            IConfiguration           config = BuildConfigurationForCredential(WrongTypesUserCredentialConfigContents);
            JsonCredentialParameters credentialParameters = config.GetSection("GoogleCredential").Get <JsonCredentialParameters>();

            // These are parsed as string. Nothing we can do our side.
            Assert.Equal("1", credentialParameters.ClientId);
            Assert.Equal("2", credentialParameters.ClientSecret);
            Assert.Equal("True", credentialParameters.RefreshToken);
            Assert.Equal("False", credentialParameters.ProjectId);

            GoogleCredential credential = GoogleCredential.FromJsonParameters(credentialParameters);

            var userCred = Assert.IsType <UserCredential>(credential.UnderlyingCredential);

            Assert.False(credential.IsCreateScopedRequired);
            Assert.Equal("True", userCred.Token.RefreshToken);
            var flow = (GoogleAuthorizationCodeFlow)userCred.Flow;

            Assert.Equal("1", flow.ClientSecrets.ClientId);
            Assert.Equal("2", flow.ClientSecrets.ClientSecret);
            Assert.Equal("False", flow.ProjectId);
            Assert.Equal("QUOTA_PROJECT", userCred.QuotaProject);
        }