public static void Main(string[] args) { var credential = GoogleCredential.GetApplicationDefault() .CreateScoped(IamService.Scope.CloudPlatform); var service = new IamService(new IamService.Initializer { HttpClientInitializer = credential }); string fullResourceName = args[0]; // [START iam_view_grantable_roles] var request = new QueryGrantableRolesRequest { FullResourceName = fullResourceName }; var response = service.Roles.QueryGrantableRoles(request).Execute(); foreach (var role in response.Roles) { Console.WriteLine("Title: " + role.Title); Console.WriteLine("Name: " + role.Name); Console.WriteLine("Description: " + role.Description); Console.WriteLine(); } // [END iam_view_grantable_roles] }
public static GoogleCredential FetchCredential(IConfiguration configuration) { // Use the default credentials if the environment variable is set. if (Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") != null) { return(GoogleCredential.GetApplicationDefault()); } // If we've got an Azure KeyVault configuration, we'll use that string secretUri = configuration["APPSETTING_SecretUri"]; string clientId = configuration["APPSETTING_ClientId"]; string clientSecret = configuration["APPSETTING_ClientSecret"]; // But if none of the environment variables has been specified, expect that // we're running on Google Cloud Platform with implicit credentials. // TODO: Autodetect if we're on GCP and only use the default credentials then. if (secretUri == null && clientId == null && clientSecret == null) { return(GoogleCredential.GetApplicationDefault()); } ClientCredential credential = new ClientCredential(clientId, clientSecret); var secret = GetKeyVaultSecret(credential, secretUri); return(GoogleCredential.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(secret)))); }
private void ConfigureFireBase() { FirebaseApp.Create(new AppOptions { Credential = GoogleCredential.GetApplicationDefault() }); }
internal RoundRobinPool(int size, string projectId) { ICredential credential = GoogleCredential.GetApplicationDefault(); _pool = Enumerable .Range(0, size) .Select(_ => CreateFirestoreDb()) .ToArray(); FirestoreDb CreateFirestoreDb() { // This code forces each channel to really use a different network connection. // Without this, different .NET Channel objects can end up using the same underlying // connection due to pooling in the C-core layer of gRPC. // Note: it would be nice to have a simpler way of doing this. var channel = new Channel( FirestoreClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials(), new ChannelOption[] { new ChannelOption("grpc_gcp.client_channel.id", Guid.NewGuid().ToString()) }); var client = new FirestoreClientBuilder { CallInvoker = channel.CreateCallInvoker() }.Build(); return(FirestoreDb.Create(projectId, client)); } }
private static IEnumerable <string> GetBlocksFromGoogleFile(string fileName) { // If you don't specify credentials when constructing the client, the // client library will look for credentials in the environment. var credential = GoogleCredential.GetApplicationDefault(); var storage = StorageClient.Create(credential); // Make an authenticated API request. var file = storage.GetObject("bitcoin-flat-bucket", fileName); using (var googleStream = new MemoryStream()) { storage.DownloadObject(file, googleStream); var full = googleStream.ToArray(); googleStream.Position = 0; using (GZipStream decompressionStream = new GZipStream(googleStream, CompressionMode.Decompress)) { using (var ms = new MemoryStream()) { decompressionStream.CopyTo(ms); var fileContents = System.Text.Encoding.Default.GetString(ms.ToArray()); var blocksHexEncoded = fileContents.Split(Environment.NewLine) .Where(l => !string.IsNullOrEmpty(l)); return(blocksHexEncoded); } } } }
public static void InitFcm(this IServiceCollection services) { FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); }
public async Task SendInformMessage(List <string> ids, string message) { var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); List <Message> messages = new List <Message>(); foreach (var id in ids) { messages.Add(new Message { Token = id, // Data = new Dictionary<string, string> //{ // { "message",message } //}, Notification = new Notification { Title = "уведомление", Body = message } }); } await FirebaseMessaging.DefaultInstance.SendAllAsync(messages); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = Environment.GetEnvironmentVariable("JWT_AUTHORITY"); //options.SecurityTokenValidators.Clear(); //options.SecurityTokenValidators.Add(new CustomTokenValidator()); options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Environment.GetEnvironmentVariable("JWT_AUTHORITY"), ValidAudience = Environment.GetEnvironmentVariable("JWT_AUDIENCE") }; }); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault() }); }
/// <summary> /// 测试google授权 /// </summary> /// <param name="projectId"></param> /// <returns></returns> public object AuthImplicit(string projectId) { try { string credentialPath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"); if (credentialPath == null) { string credential_path = @"/Users/mac/Library/Google/TranslationAPI-0a258748402c.json"; Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path); } Console.WriteLine(credentialPath); // If you don't specify credentials when constructing the client, the // client library will look for credentials in the environment. var credential = GoogleCredential.GetApplicationDefault(); var storage = StorageClient.Create(credential); // Make an authenticated API request. var buckets = storage.ListBuckets(projectId); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name); } } catch (Google.GoogleApiException ex) { Console.WriteLine(ex.Message); } return(null); }
public static int Main(string[] args) { // Read projectId from args if (args.Length != 1) { Console.WriteLine("Usage: Project ID must be passed as first argument."); Console.WriteLine(); return(1); } string projectId = args[0]; // Smoke test against the Google Container Analysis implementation, using // a known endpoint. // Create client var channelCredential = GoogleCredential.GetApplicationDefault().ToChannelCredentials(); var channel = new Channel("containeranalysis.googleapis.com", channelCredential); GrafeasClient client = GrafeasClient.Create(channel); // Call API method ProjectName projectName = new ProjectName(projectId); PagedEnumerable <ListNotesResponse, Note> notes = client.ListNotes(projectName, ""); // Show the result foreach (Note note in notes) { Console.WriteLine(note); } // Success Console.WriteLine("Smoke test passed OK"); return(0); }
public void Initialize() { FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); }
private void InitDefaultClient() { GoogleCredential credential = GoogleCredential.GetApplicationDefault(); var channel = new Channel(Target, credential.ToChannelCredentials()); client = new Bigtable.BigtableClient(channel); }
/// <summary> /// Add multiple students in a specified course. /// </summary> /// <param name="courseId">Id of the course to add students.</param> /// <param name="studentEmails">Email address of the students.</param> public static void ClassroomBatchAddStudents(string courseId, List <string> studentEmails) { try { /* Load pre-authorized user credentials from the environment. * TODO(developer) - See https://developers.google.com/identity for * guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(ClassroomService.Scope.ClassroomRosters); // Create Classroom API service. var service = new ClassroomService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Classroom Snippets" }); var batch = new BatchRequest(service, "https://classroom.googleapis.com/batch"); BatchRequest.OnResponse <Student> callback = (student, error, i, message) => { if (error != null) { Console.WriteLine("Error adding student to the course: {0}", error.Message); } else { Console.WriteLine("User '{0}' was added as a student to the course.", student.Profile.Name.FullName); } }; foreach (var studentEmail in studentEmails) { var student = new Student() { UserId = studentEmail }; var request = service.Courses.Students.Create(student, courseId); batch.Queue <Student>(request, callback); } Task.WaitAll(batch.ExecuteAsync()); } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found"); } else if (e is GoogleApiException) { Console.WriteLine("Course does not exist."); } else { throw; } } }
static void Main(string[] args) { GoogleCredential credential = GoogleCredential.GetApplicationDefault(); if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { CloudResourceManagerService.Scope.CloudPlatformReadOnly }); } var crmService = new CloudResourceManagerService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); var request = new ProjectsResource.ListRequest(crmService); while (true) { var result = request.Execute(); foreach (var project in result.Projects) { Console.WriteLine(project.ProjectId); } if (string.IsNullOrEmpty(result.NextPageToken)) { break; } request.PageToken = result.NextPageToken; } }
public IActionResult Create(IFormFile vehicleImage, string name, string rideService) { string bucketname = _config.GetSection("AppSettings").GetSection("LogosBucket").Value; Vehicle newVehicle = new Vehicle(); newVehicle.VehicleID = Guid.NewGuid(); newVehicle.Name = name; newVehicle.Category = rideService; using (var myFile = vehicleImage.OpenReadStream()) { var credential = GoogleCredential.GetApplicationDefault(); var storage = StorageClient.Create(credential); var filePath = @"vehicleImages/" + newVehicle.VehicleID + "/" + vehicleImage.FileName; storage.UploadObject(bucketname, filePath, null, myFile); newVehicle.ImageURL = filePath; } newVehicle.Owner = User.Identity.Name; _vehiclesRepo.AddVehicle(newVehicle); ViewBag.Categories = _cacheRepository.GetCategories(); return(View()); }
public void CreateClientWithEmptyOptions() { GoogleCredential credential = GoogleCredential.GetApplicationDefault(); invoker = new GcpCallInvoker(Target, credential.ToChannelCredentials()); client = new Bigtable.BigtableClient(invoker); MutateRowRequest mutateRowRequest = new MutateRowRequest { TableName = TableName, RowKey = ByteString.CopyFromUtf8(RowKey) }; Mutation mutation = new Mutation { SetCell = new Mutation.Types.SetCell { FamilyName = ColumnFamily, ColumnQualifier = ByteString.CopyFromUtf8(ColumnQualifier), Value = ByteString.CopyFromUtf8(TestValue), } }; mutateRowRequest.Mutations.Add(mutation); client.MutateRow(mutateRowRequest); Assert.AreEqual(1, invoker.GetChannelRefsForTest().Count); }
static void Main(string[] args) { string projectId = "utility-vista-196902"; // If you don't specify credentials when constructing the client, the // client library will look for credentials in the environment. //var jsonCredentials = System.IO.File.ReadAllText(@".\client_secret_.json"); var credential = GoogleCredential.GetApplicationDefault(); // Instantiates a client. StorageClient storageClient = StorageClient.Create(credential); // The name for the new bucket. string bucketName = projectId + "-test-bucket"; try { // Creates the new bucket. storageClient.UploadObject(bucketName, "name.txt", "application/text", File.OpenRead(@".\client_secret_.json"), null); Console.WriteLine($"Bucket {bucketName} created."); } catch (Google.GoogleApiException e) when(e.Error.Code == 409) { // The bucket already exists. That's fine. Console.WriteLine(e.Error.Message); } }
static async Task Main(string[] args) { var emails = Environment.GetEnvironmentVariable("SU_EMAILS").Split(","); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault() }); UserRecord createUser = await FirebaseAuth.DefaultInstance .GetUserByEmailAsync("*****@*****.**"); var result = await FirebaseAuth.DefaultInstance.UpdateUserAsync(new UserRecordArgs() { Uid = createUser.Uid, Password = "******" }); foreach (var email in emails) { UserRecord user = await FirebaseAuth.DefaultInstance .GetUserByEmailAsync(email); if (user.EmailVerified) { var claims = new Dictionary <string, object>() { { "role", "SU" }, }; await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(user.Uid, claims); } } }
public object AuthImplicit(string projectId) { GoogleCredential credential = GoogleCredential.GetApplicationDefault(); // Inject the Cloud Storage scope if required. if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { StorageService.Scope.DevstorageReadOnly }); } var storage = new StorageService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "gcloud-dotnet/2.2.1", }); var request = new BucketsResource.ListRequest(storage, projectId); var requestResult = request.Execute(); foreach (var bucket in requestResult.Items) { Console.WriteLine(bucket.Name); } return(null); }
private ChannelCredentials GetCredentials() { // Only build these once. if (_credentials == null) { // NOTE: extend here to add other auth mechanisms. if (!_jsonAuthFile.IsNullOrEmpty()) { // Authenticate using a reference to json files. _credentials = GoogleCredential.FromFile(_jsonAuthFile).ToChannelCredentials(); } else { // Default method, which takes the environment variable "GOOGLE_APPLICATION_CREDENTIALS" with the credential file path. // Firstly, verify the credentials have been set as expected - throw error if not. var credentialLocation = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"); if (credentialLocation.IsNullOrEmpty() || File.Exists(credentialLocation) == false) { throw new InvalidOperationException("Environment variable \"GOOGLE_APPLICATION_CREDENTIALS\" must exist and must point to a valid credential json file"); } // Use default credentials. _credentials = GoogleCredential.GetApplicationDefault().ToChannelCredentials(); } } return(_credentials); }
public void UploadObject(string bucketName, Stream stream, string objectName, string contentType) { #region validation if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentException(nameof(bucketName)); } if (stream == null || stream.Length <= 0) { throw new ArgumentException(nameof(stream)); } if (string.IsNullOrEmpty(objectName)) { throw new ArgumentException(nameof(objectName)); } if (string.IsNullOrEmpty(contentType)) { throw new ArgumentException(nameof(contentType)); } #endregion // If you don't specify credentials when constructing the client, the // client library will look for credentials in the environment. GoogleCredential googleCredential = GoogleCredential.GetApplicationDefault(); if (googleCredential == null) { throw new ArgumentNullException(nameof(GoogleCredential)); } var storage = StorageClient.Create(googleCredential); storage.UploadObject(bucketName, objectName, contentType, stream); }
public SendNotificationService() { FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); }
private static AppOptions GetOptionsFromEnvironment() { return(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); }
// [END fs_count_indexes] // Creates an index for a given collection in a project. // [START fs_create_index] private static async Task CreateIndex(string project, string collectionId, string field1, string order1, string field2, string order2) { GoogleCredential credential = GoogleCredential.GetApplicationDefault(); // Inject the Cloud Platform scope if required. if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(new[] { "https://www.googleapis.com/auth/cloud-platform" }); } HttpClient http = new Google.Apis.Http.HttpClientFactory() .CreateHttpClient( new Google.Apis.Http.CreateHttpClientArgs() { ApplicationName = "Google Cloud Platform Firestore Sample", GZipEnabled = true, Initializers = { credential }, }); IndexContent indexContent = new IndexContent(collectionId, field1, order1, field2, order2); string jsonRequest = JsonConvert.SerializeObject(indexContent); string uriString = "https://firestore.googleapis.com/v1beta1/projects/" + project + "/databases/(default)/indexes"; UriBuilder uri = new UriBuilder(uriString); await http.PostAsync(uri.Uri, new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json")); }
internal static void InitCustomApp() { var defaultOptions = new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }; var otherAppConfig = new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }; // [START access_services_nondefault] // Initialize the default app var defaultApp = FirebaseApp.Create(defaultOptions); // Initialize another app with a different config var otherApp = FirebaseApp.Create(otherAppConfig, "other"); Console.WriteLine(defaultApp.Name); // "[DEFAULT]" Console.WriteLine(otherApp.Name); // "other" // Use the shorthand notation to retrieve the default app's services var defaultAuth = FirebaseAuth.DefaultInstance; // Use the otherApp variable to retrieve the other app's services var otherAuth = FirebaseAuth.GetAuth(otherApp); // [END access_services_nondefault] }
public static void Main(string[] args) { // Get credentials GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(IamService.Scope.CloudPlatform); // Create the Cloud IAM service object IamService service = new IamService(new IamService.Initializer { HttpClientInitializer = credential }); // Call the Cloud IAM Roles API ListRolesResponse response = service.Roles.List().Execute(); IList <Role> roles = response.Roles; // Process the response foreach (Role role in roles) { Console.WriteLine("Title: " + role.Title); Console.WriteLine("Name: " + role.Name); Console.WriteLine("Description: " + role.Description); Console.WriteLine(); } }
public QuickStartTest() { // Check for _projectId and throw exception if empty _projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID"); if (_projectId == null) { throw new ArgumentNullException("GOOGLE_PROJECT_ID", "Environment variable not set"); } // Create service account for test var credential = GoogleCredential.GetApplicationDefault() .CreateScoped(IamService.Scope.CloudPlatform); _iamService = new IamService( new IamService.Initializer { HttpClientInitializer = credential }); var request = new CreateServiceAccountRequest { AccountId = "iam-test-account" + DateTime.UtcNow.Millisecond, ServiceAccount = new ServiceAccount { DisplayName = "iamTestAccount" } }; _serviceAccount = _iamService.Projects.ServiceAccounts.Create( request, "projects/" + _projectId).Execute(); }
public async Task <IActionResult> SignInUser() { var form = Request.Form; try { if (FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance == null) { //string credential_path = @"C:\Users\ghrey\Downloads\ScrumManager-c7ce2bf2810c.json"; //Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path); var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault() }); } var verifiedToken = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(form["Token"]); var identity = new ClaimsIdentity(verifiedToken.ToClaims(), JwtBearerDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(Json(new { redirect = Url.Action("Index") })); } catch (Exception ex) { Debug.WriteLine(ex.Message); return(Error()); } }
public static Role CreateRole(string name, string projectId, string title, string description, IList <string> permissions, string stage) { var credential = GoogleCredential.GetApplicationDefault() .CreateScoped(IamService.Scope.CloudPlatform); var service = new IamService(new IamService.Initializer { HttpClientInitializer = credential }); var role = new Role { Title = title, Description = description, IncludedPermissions = permissions, Stage = stage }; var request = new CreateRoleRequest { Role = role, RoleId = name }; role = service.Projects.Roles.Create(request, "projects/" + projectId).Execute(); Console.WriteLine("Created role: " + role.Name); return(role); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseCors("CorsPolicy"); app.UseSignalR(routes => { routes.MapHub <ChatHub>("/chathub"); }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); }