public void CreateWithUser() { var serviceAccountCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("MyId", "MyTokenServerUrl") { Clock = new MockClock(), AccessMethod = new DummyAccessMethod(), HttpClientFactory = new DummyHttpClientFactory(), DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.Exception, // This is not the default ProjectId = "a_project_id", User = "******", Scopes = new[] { "scope1" }, }.FromPrivateKey(PrivateKey)); var cred1 = GoogleCredential.FromServiceAccountCredential(serviceAccountCred); var cred2 = cred1.CreateWithUser("user2"); var svc1 = (ServiceAccountCredential)cred1.UnderlyingCredential; var svc2 = (ServiceAccountCredential)cred2.UnderlyingCredential; Assert.Same(serviceAccountCred, svc1); Assert.NotSame(serviceAccountCred, svc2); Assert.Same(svc1.Id, svc2.Id); Assert.Same(svc1.TokenServerUrl, svc2.TokenServerUrl); Assert.Same(svc1.Clock, svc2.Clock); Assert.Same(svc1.AccessMethod, svc2.AccessMethod); Assert.Same(svc1.HttpClientFactory, svc2.HttpClientFactory); Assert.Equal(svc1.DefaultExponentialBackOffPolicy, svc2.DefaultExponentialBackOffPolicy); Assert.Same(svc1.ProjectId, svc2.ProjectId); Assert.NotSame(svc1.User, svc2.User); Assert.Same(svc1.Scopes, svc2.Scopes); Assert.Equal("user1", svc1.User); Assert.Equal("user2", svc2.User); }
private IKeyManagement GetGoogleCloudKeyManagment() { var location = Configuration.GetValue <string>("KeyManagement:GoogleKms:Location"); var keyRingName = Configuration.GetValue <string>("KeyManagement:GoogleKms:KeyRingName"); var protectionLevel = Configuration.GetValue <string>("KeyManagement:GoogleKms:ProtectionLevel"); var credentialsPath = Configuration.GetValue <string>("KeyManagement:GoogleKms:CredentialsPath"); var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(File.OpenRead(credentialsPath)); var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential); if (credentials.IsCreateScopedRequired) { credentials = credentials.CreateScoped(new[] { CloudKMSService.Scope.CloudPlatform }); } var kmsService = new CloudKMSService(new BaseClientService.Initializer { HttpClientInitializer = credentials, GZipEnabled = true }); return(new GoogleCloudKeyManagment( kmsService, serviceAccountCredential.ProjectId, keyRingName, location, protectionLevel)); }
/// <summary> /// Applies scopes when they're available, and potentially specifies a preference for /// using self-signed JWTs. /// </summary> private GoogleCredential ApplyScopes(GoogleCredential original) { if (!original.IsCreateScopedRequired || _scopes.Count == 0) { return(original); } var scoped = original.CreateScoped(_scopes); return(_useJwtWithScopes && scoped.UnderlyingCredential is ServiceAccountCredential serviceCredential ? GoogleCredential.FromServiceAccountCredential(serviceCredential.WithUseJwtAccessWithScopes(true)) : scoped); }
public GoogleStorageService(string name, IOptions <GoogleSettings> googleSettings, bool allowDirectDownload, bool allowDirectUpload, ILogger <StorageServiceProvider> logger) { Type = StorageServiceProvider.GOOGLE_STORAGE; Name = name; GoogleSettings = googleSettings.Value; SupportsDirectDownload = false; AllowDirectDownload = allowDirectDownload; SupportsDirectUpload = false; AllowDirectUpload = allowDirectUpload; _logger = logger; // use a tool like this to escape the Google Service Account Credentials JSON file so you can add it to appsettings.json: // https://www.freeformatter.com/json-escape.html var sacByteArray = Encoding.UTF8.GetBytes(GoogleSettings.ServiceAccountCredential); var sacStream = new MemoryStream(sacByteArray); var credential = GoogleCredential.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(sacStream)); _googleClient = StorageClient.Create(credential); }
public async Task FromServiceAccountCredential_FetchesOicdToken() { var clock = new MockClock { UtcNow = new DateTime(2020, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) }; var messageHandler = new OidcTokenSuccessMessageHandler(clock); var initializer = new ServiceAccountCredential.Initializer("MyId", "http://will.be.ignored") { Clock = clock, ProjectId = "a_project_id", HttpClientFactory = new MockHttpClientFactory(messageHandler) }; var serviceAccountCredential = new ServiceAccountCredential(initializer.FromPrivateKey(ServiceAccountCredentialTests.PrivateKey)); var googleCredential = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential); var oidcToken = await googleCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience("audience")); Assert.Equal("very_fake_access_token_1", await oidcToken.GetAccessTokenAsync()); }
public async Task FromServiceAccountCredential_FetchesOidcToken() { // A little bit after the tokens returned from OidcTokenFakes were issued. var clock = new MockClock(new DateTime(2020, 5, 13, 15, 0, 0, 0, DateTimeKind.Utc)); var messageHandler = new OidcTokenResponseSuccessMessageHandler(); var initializer = new ServiceAccountCredential.Initializer("MyId", "http://will.be.ignored") { Clock = clock, ProjectId = "a_project_id", HttpClientFactory = new MockHttpClientFactory(messageHandler) }; var serviceAccountCredential = new ServiceAccountCredential(initializer.FromPrivateKey(ServiceAccountCredentialTests.PrivateKey)); var googleCredential = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential); // The fake Oidc server returns valid tokens (expired in the real world for safty) // but with a set audience that lets us know if the token was refreshed or not. var oidcToken = await googleCredential.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience("will.be.ignored")); var signedToken = SignedToken <Header, Payload> .FromSignedToken(await oidcToken.GetAccessTokenAsync()); Assert.Equal("https://first_call.test", signedToken.Payload.Audience); }
public GoogleCloudKeyManagmentTests() { mConfiguration = new ConfigurationBuilder() .AddJsonFile("settings.json") .AddEnvironmentVariables().Build(); var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Credentials")); writer.Flush(); stream.Position = 0; var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(stream); var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential); if (credentials.IsCreateScopedRequired) { credentials = credentials.CreateScoped(new[] { CloudKMSService.Scope.CloudPlatform }); } mCloudKmsService = new CloudKMSService(new BaseClientService.Initializer { HttpClientInitializer = credentials, GZipEnabled = true }); var location = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Location"); var keyRingName = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:KeyRingName"); var protectionLevel = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:ProtectionLevel"); mGoogleCloudKeyManagement = new GoogleCloudKeyManagment( mCloudKmsService, serviceAccountCredential.ProjectId, keyRingName, location, protectionLevel); }
/// <summary> /// Creates a cache which will apply the specified scopes to the default application credentials /// if they require any. /// </summary> /// <param name="serviceMetadata">The metadata of the service the credentials will be used with. Must not be null.</param> internal DefaultChannelCredentialsCache(ServiceMetadata serviceMetadata) { UseJwtAccessWithScopes = serviceMetadata.SupportsScopedJwts; // In theory, we don't actually need to store the scopes as field in this class. We could capture a local variable here. // However, it won't be any more efficient, and having the scopes easily available when debugging could be handy. _scopes = serviceMetadata.DefaultScopes; _lazyScopedDefaultChannelCredentials = new Lazy <Task <ChannelCredentials> >(() => Task.Run(async() => { var appDefaultCredentials = await GoogleCredential.GetApplicationDefaultAsync().ConfigureAwait(false); if (appDefaultCredentials.IsCreateScopedRequired) { appDefaultCredentials = appDefaultCredentials.CreateScoped(_scopes); } if (appDefaultCredentials.UnderlyingCredential is ServiceAccountCredential serviceCredential && serviceCredential.UseJwtAccessWithScopes != UseJwtAccessWithScopes) { appDefaultCredentials = GoogleCredential.FromServiceAccountCredential(serviceCredential.WithUseJwtAccessWithScopes(UseJwtAccessWithScopes)); } return(appDefaultCredentials.ToChannelCredentials()); })); }
private static void ServiceAccounts(string credentialsJson, string userEmail) { LoginAsServiceAccountWithJson(credentialsJson); IList <ServiceAccountKey> serviceAccountKeys = ListKeysOfServiceAccount(userEmail); ServiceAccountKey newKey = CreateKeyOfServiceAccount(userEmail); // Call the translate API with the new key. byte[] jsonKey = Convert.FromBase64String(newKey.PrivateKeyData); Stream jsonKeyStream = new MemoryStream(jsonKey); ServiceAccountCredential credential = ServiceAccountCredential .FromServiceAccountData(jsonKeyStream); GoogleCredential googleCredential = GoogleCredential .FromServiceAccountCredential(credential); var client = TranslationClient.Create(googleCredential); var response = client.TranslateText("Hello World", "ru"); Console.WriteLine(response.TranslatedText); //DeleteKeyOfServiceAccount(newKey); // LoginWithServiceAccountKey(newKey, credentialsJson); }
public async Task SendEvent(IHiarcEvent theEvent) { try { var serializedEvent = JsonSerializer.Serialize(theEvent); var topicName = new TopicName(_pubSubSettings.ProjectId, _pubSubSettings.Topic); var sacByteArray = Encoding.UTF8.GetBytes(_pubSubSettings.ServiceAccountCredential); var sacStream = new MemoryStream(sacByteArray); var credential = GoogleCredential.FromServiceAccountCredential(ServiceAccountCredential.FromServiceAccountData(sacStream)); var createSettings = new ClientCreationSettings(credentials: credential.ToChannelCredentials()); var publisher = await CreateAsync(topicName, clientCreationSettings : createSettings); var messageId = await publisher.PublishAsync(serializedEvent); await publisher.ShutdownAsync(TimeSpan.FromSeconds(10)); _logger.LogDebug($"Successfully sent event '{theEvent.Event}' to '{this.Name}'. Payload: {serializedEvent}"); } catch (Exception ex) { _logger.LogError($"Failed to send event '{theEvent.Event}' to '{this.Name}'. Exception: {ex.Message}"); } }
private GoogleCredential GetCredential() { return(GoogleCredential.FromServiceAccountCredential(GetServiceAccount())); }
public static GoogleCredential GetServiceCredentialWithJwtFlag() { ServiceAccountCredential credential = (ServiceAccountCredential)s_serviceCredential.Value.UnderlyingCredential; return(GoogleCredential.FromServiceAccountCredential(credential.WithUseJwtAccessWithScopes(true))); }