{"id":21355063,"url":"https://github.com/salrashid123/gcpsamples","last_synced_at":"2025-07-12T22:32:38.120Z","repository":{"id":36773912,"uuid":"41080629","full_name":"salrashid123/gcpsamples","owner":"salrashid123","description":"Simple \"Hello world\" samples for accessing Google Cloud APIs in (node,dotnet,java,golang,python)","archived":false,"fork":false,"pushed_at":"2023-02-25T10:16:35.000Z","size":1225,"stargazers_count":100,"open_issues_count":11,"forks_count":25,"subscribers_count":6,"default_branch":"master","last_synced_at":"2023-02-28T09:56:44.552Z","etag":null,"topics":["cloud-api","cloud-client","google-cloud","google-cloud-platform"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/salrashid123.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-08-20T06:58:28.000Z","updated_at":"2023-02-28T09:56:44.552Z","dependencies_parsed_at":"2022-07-12T16:12:45.129Z","dependency_job_id":null,"html_url":"https://github.com/salrashid123/gcpsamples","commit_stats":null,"previous_names":[],"tags_count":null,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/salrashid123%2Fgcpsamples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/salrashid123%2Fgcpsamples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/salrashid123%2Fgcpsamples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/salrashid123%2Fgcpsamples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/salrashid123","download_url":"https://codeload.github.com/salrashid123/gcpsamples/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225839598,"owners_count":17532308,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloud-api","cloud-client","google-cloud","google-cloud-platform"],"created_at":"2024-11-22T04:15:42.644Z","updated_at":"2024-11-22T04:15:43.300Z","avatar_url":"https://github.com/salrashid123.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Google Cloud Platform API hello world samples\n\n####  samples provided as-is without warranty\n\nSample code demonstrating various Auth mechanism for Google Cloud Platform APIs.\n\nPlease refer to official documentation for usage and additional samples/usage.\n\n[Google Authentication Samples](https://cloud.google.com/docs/authentication)\n\n***  \n\n### Application Default Credentials\n\nThe samples use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials) which uses credentials in the following order as described in the link.  Set the environment variable to override.  \n\nYou can always specify the target source to acquire credentials by using intent specific targets such as:  ComputeCredentials, UserCredentials or ServiceAccountCredential.\n\nThere are two types of client libraries you can use to connect to Google APIs:  \n* Google Cloud Client Libraries\n* Gooogle API Client Libraries  \u003c\u003c note: this repo now omits this api mechanism (for the most part)\n\nThe basic differences is the Cloud Client libraries are idiomatic, has [gcloud-based emulators](https://cloud.google.com/sdk/gcloud/reference/beta/emulators/) and much easier to use.  \n\nIt is recommended to use Cloud Client Libraries whereever possible. Although this article primarily describes the API Client libraries, the python code section describes uses of Cloud Client libraries with Google Cloud Storage.\n\nFor more information, see\n\n* [Client Libraries Explained](https://cloud.google.com/apis/docs/client-libraries-explained).\n* [Google Cloud Platform Authenticatio Guide](https://cloud.google.com/docs/authentication)\n\nThis article also describes how to use IAM's serviceAccountActor role to issue access_tokens, id_tokens and JWT.  For more information on that, see [auth/tokens/](auth/tokens).\n\nThe following examples use the Oauth2 *service* to demonstrate the initialized client using Google API Client Libraries.  The first section is about the different client libraries you can use.\n\n* [Cloud Client Libraries and API Client Libraries](#googlelibraries)\n    - Cloud Client Libraries\n    - API Client Libraries\n* Cloud Client Libraries\n    - [Python](#cloud-python)\n    - [Java](#cloud-java)\n    - [Go](#cloud-go)\n    - [Node](#cloud-node)\n    - [c#](#cloud-c)\n    - [gRPC Environment Variables](#grpc-environment-variables)\n    - [GCS SignedURL with Customer Supplied Encryption Keys](gcs_csek_signedurl)\n    - [JWT Access Token](#jwt-access-token)\n* API Client Library\n    - [Python](#google-api-python)\n    - [Java](#google-api-java)\n    - [Go](#google-api-go)\n    - [Node](#google-api-nodejs)\n    - [C#](#google-api-C\u0026#35)\n* [serviceAccountActor role for impersonation](auth/tokens)\n    - access_token\n    - id_token\n    - JWT\n* [Impersonated Credentials](impersonated_credentials/)\n* [Accessing Google APIs through proxies](proxy/)\n* [Issue and Verify id_tokens](id_token/)\n* [GCS SignedURL with HMAC](gcs_hmac_signedurl)\n* [GCS keyless SignedURL](gcs_keyless_signedurl)\n* [Accessing Google APIs through proxies](proxy/)\n\nFor more inforamtion, see:\n* [oauth2 protocol](https://developers.google.com/identity/protocols/OAuth2)\n* [oauth2 service](https://developers.google.com/apis-explorer/#p/oauth2/v2/)\n* [Service Accounts](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#overview)\n\n### GoogleLibraries\nAs described in the introduciton, this section details the two types of libraries you can use to access Google Services:\n\n#### Google Cloud Client Libraries\nThese libraries are idomatic, easy to use and even support the [gcloud-based emulator framework](https://cloud.google.com/sdk/gcloud/reference/beta/emulators/).  This is the\nrecommended library set to use to access Google Cloud APIs.\n\nFor more information, see:\n\n* [Application DefaultCredentials](https://developers.google.com/identity/protocols/application-default-credentials)\n* [google-cloud](https://googlecloudplatform.github.io/google-cloud-python/)\n* [google-auth package](https://google-auth.readthedocs.io/en/latest/)\n* [google-auth Users Guide](https://google-auth.readthedocs.io/en/latest/user-guide.html)\n\nThe following example describes various ways to initialize a service account to list the Google Cloud Storage buckets the account has access to.  It also shows listing the buckets\nusing the default account currently initialized by gcloud.\n\nTo use the mechanisms here, you need to initialize gcloud's application defaults:\n\n```bash\ngcloud auth application-default login\n\n```\n\n#### Cloud Python\n\nThe following uses the google-storage client described here: [Storage Client](http://gcloud-python.readthedocs.io/en/latest/storage-client.html)\n\n\n```\nvirtualenv env\nsource env/bin/activate\npip install google-cloud-storage\n```\n\nThe following lists some of the various mechanisms to acquire credentials:\n\nList buckets using the default account on the current gcloud cli (preferred)\n\n```python\nfrom google.cloud import storage\n\nclient = storage.Client()\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\nList buckets using gcloud cli explicit credential and project\n\n```python\nfrom google.cloud import storage\nimport google.auth\n\ncredentials, project = google.auth.default()    \nclient = storage.Client(credentials=credentials)\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\nList buckets using an environment variable and then google.auth.default() credentials.\n\n```python\nfrom google.cloud import storage\nimport google.auth\nimpot os\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"YOUR_JSON_CERT.json\"\ncredentials, project = google.auth.default()\nif credentials.requires_scopes:\n  credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_write'])\nclient = storage.Client(credentials=credentials)\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\nList buckets using a service_account oauth2 object directly\n\n```python\nfrom google.cloud import storage\nimport google.auth\nfrom google.oauth2 import service_account\n\ncredentials = service_account.Credentials.from_service_account_file('YOUR_JSON_CERT.json')\nif credentials.requires_scopes:\n  credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_write'])\n\nclient = storage.Client(credentials=credentials)\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\nList buckets using the storage client directly loading the certificate:\n\n```python\nfrom google.cloud import storage\n\nclient = storage.Client.from_service_account_json(\"YOUR_JSON_CERT.json\")\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\n##### Iterators\n\nsee\n - [google cloud python iterators](https://gcloud-python.readthedocs.io/en/stable/core/iterators.html)\n - [page iterators](https://googlecloudplatform.github.io/google-cloud-python/latest/core/page_iterator.html)\n\n\n* Logging:\n\n```python\nimport os\nimport pprint\nfrom google.cloud import logging\n\nfrom google.cloud.logging import ASCENDING\nfrom google.cloud.logging import DESCENDING\n\npp = pprint.PrettyPrinter(indent=1)\n\nFILTER = 'resource.type=\"gae_app\" AND logName=\"projects/your-project/logs/appengine.googleapis.com%2Frequest_log\" AND protoPayload.resource=\"/\"'\n\nclient = logging.Client()\n\niterator = client.list_entries(filter_=FILTER, order_by=DESCENDING)\nfor page in iterator.pages:\n  print('    Page number: %d' % (iterator.page_number,))\n  print('  Items in page: %d' % (page.num_items,))\n  print('Items remaining: %d' % (page.remaining,))\n  print('Next page token: %s' % (iterator.next_page_token,))  \n  print('----------------------------')\n  for entry in page:\n      print(entry.timestamp)\n```\n\n* Monitoring:\n\n```python\n\n# virtualenv env\n# source env/bin/activate\n# pip install google-cloud-monitoring==0.30.0\n\nimport datetime, time\nimport pprint\nfrom google.cloud import monitoring_v3\nfrom google.cloud.monitoring_v3.query import Query\n\nclient = monitoring_v3.MetricServiceClient()\n\nmetric_type = 'serviceruntime.googleapis.com/api/request_count'\nresource_type = 'consumed_api'\nservice = 'logging.googleapis.com'\n\nnow = datetime.datetime.utcnow()\nfifteen_mins_ago =  now - datetime.timedelta(minutes=15)\n\nq = Query(client, project='YOUR_PROJECT', metric_type=metric_type, minutes=10)\nq.select_interval(end_time=now,start_time=fifteen_mins_ago)\nq.select_resources(resource_type=resource_type, service=service)\n\nfor timeseries in q.iter():\n  print()'========== Metric: ')\n  #pprint.pprint(timeseries)\n  print()'========== Points: ')\n  for p in timeseries.points:\n   print(repr(p))\n   print(str(p.start_time) + ' --\u003e ' + str(p.end_time) + '  : [' +  str(p.value.get('bucketCounts')) + ']')\n  print('-----------------')\n\n```\n\n##### Using google.auth for GoogleAPIs\n\n\nThe following shows transport authorization for the original Google APIs\n\n```python\nimport oauth2client\nfrom oauth2client.client import GoogleCredentials\nimport httplib2\n\nhttp = httplib2.Http()\ncredentials = GoogleCredentials.get_application_default()\nif credentials.create_scoped_required():\n  credentials = credentials.create_scoped(scopes)\nhttp = credentials.authorize(http)\n```\n\nIf you need to use the more recent Google Cloud Auth library, you need to cast the transport:\n\n-  [http://google-auth.readthedocs.io/en/latest/reference/google.auth.html](http://google-auth.readthedocs.io/en/latest/reference/google.auth.html)\n-  [ https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2]( https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2)\n\n\n```python\nimport google.auth\nimport google_auth_httplib2\n\nscopes = ['https://www.googleapis.com/auth/devstorage.read_write']\ncredentials, project = google.auth.default(scopes=scopes)\nhttp =  google_auth_httplib2.AuthorizedHttp(credentials)\n```\n\nor preferably init a cloud API:\n\n```python\nfrom google.cloud import storage\nimport google.auth\nfrom google.oauth2 import service_account\nimport os\n\n#credentials = service_account.Credentials.from_service_account_file('YOUR_JSON_CERT.json')\n#if credentials.requires_scopes:\n#  credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_write'])\n#client = storage.Client(credentials=credentials)\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"/path/to/svc_account.json\"\ncredentials, project = google.auth.default()    \nclient = storage.Client(credentials=credentials)\nbuckets = client.list_buckets()\nfor bkt in buckets:\n  print(bkt)\n```\n\n##### Logging_Cloud_python\n\nIf you want to enable trace logging with `google-cloud-python*` library set,\n\n```python\n#!/usr/bin/python\n\nfrom google.cloud import bigquery\nfrom six.moves import http_client\n\nhttp_client.HTTPConnection.debuglevel = 5\n\nclient = bigquery.Client()\nquery_job = client.query(\"\"\"\n        SELECT timestamp\nFROM\n `your-project.gae_request_logs.appengine_googleapis_com_request_log_20161119`\nORDER BY timestamp DESC\nLIMIT\n 4;\"\"\")\n\nresults = query_job.result()\nfor row in results:\n        print(row)\n```\n\n#### Cloud Java\n\n* [http://googlecloudplatform.github.io/google-cloud-java/0.8.0/index.html](http://googlecloudplatform.github.io/google-cloud-java/0.8.0/index.html)\n* [StorageExample](https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java)\n* [Java Cloud Examples](https://github.com/GoogleCloudPlatform/java-docs-samples)\n* [Google Extensions for Java (GAX)](http://googleapis.github.io/gax-java/)\n\nThe following describes using java default credentials.  You can explictly _setCredentials()_ while initializing a service but that is not recommended as the code is not portable\n\nThe various credential types can be found here:\n* [com.google.auth.oauth2](https://github.com/google/google-auth-library-java/tree/master/oauth2_http/java/com/google/auth/oauth2)\n* [Credential Types](https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http)\n\nThe samples conained within\n\n- [auth/service/javaapp](auth/service/javaapp)\n- [auth/compute/javaapp](auth/compute/javaapp)\n\nShows one sample app that uses both library types.  At the time of writing (7/7/18), there is a conflict between the grpc dependencies and google apis.\n\nWHich means, if you use GoogleAPIs, comment out the sections for Cloud API in the pom and .java files:\n\nfor Cloud APIs, use:\n- pom.xml\n```xml\n  \u003cdependency\u003e\n      \u003cgroupId\u003ecom.google.cloud\u003c/groupId\u003e\n      \u003cartifactId\u003egoogle-cloud-storage\u003c/artifactId\u003e\n      \u003cversion\u003ezzzz\u003c/version\u003e\n  \u003c/dependency\u003e\n\n  \u003cdependency\u003e\n    \u003cgroupId\u003ecom.google.cloud\u003c/groupId\u003e\n    \u003cartifactId\u003egoogle-cloud-pubsub\u003c/artifactId\u003e\n    \u003cversion\u003eyyyy\u003c/version\u003e\n  \u003c/dependency\u003e\n```\n\n```java\nimport com.google.cloud.storage.Bucket;\nimport com.google.cloud.storage.Storage;\nimport com.google.cloud.storage.StorageOptions;\nimport com.google.cloud.storage.Blob;\nimport com.google.cloud.storage.Blob.BlobSourceOption;\nimport com.google.cloud.storage.BlobId;\nimport com.google.cloud.storage.BlobInfo;\n\nimport com.google.cloud.storage.Storage.SignUrlOption;\nimport java.util.concurrent.TimeUnit;\nimport java.net.URL;\nimport java.util.Iterator;\nimport java.io.FileInputStream;\n\n\n//import com.google.auth.oauth2.ServiceAccountCredentials;\n\n// Using Google Cloud APIs with service account file\n// You can also just export an export GOOGLE_APPLICATION_CREDENTIALS and use StorageOptions.defaultInstance().service()\n// see https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http\n/*\nStorage storage_service = StorageOptions.newBuilder()\n\t\t\t.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(\"/path/to/your/certificate.json\")))\n\t\t\t.build()\n\t\t\t.getService();\t\t\t\n*/\n\nStorage storage_service = StorageOptions.newBuilder()\n\t.build()\n\t.getService();\nfor (Bucket b : storage_service.list().iterateAll()){\n  System.out.println(b);\n}\n\n// You can also use the client to generate a signed URL:\nURL signedUrl = storage_service.signUrl(BlobInfo.newBuilder(\"your_project\", \"a.txt\").build(), 60,  TimeUnit.SECONDS);\nSystem.out.println(signedUrl);\n```\n\n##### Proxy Server Settings\n\nsee [proxy/README.md](proxy/README.md)\n\n\n##### Async Futures\n\nsee [Example](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java#L40)\n\n```java\n\nimport com.google.iam.v1.GetIamPolicyRequest;\nimport com.google.iam.v1.Policy;\nimport com.google.iam.v1.SetIamPolicyRequest;\nimport com.google.iam.v1.Binding;\nimport com.google.cloud.Role;\n\n    // setup topicadmin client using the bit above\n\tTopicAdminClient topicClient =\n\t  TopicAdminClient.create(\n\t\t  TopicAdminSettings.newBuilder()\n\t\t\t  .setTransportChannelProvider(channelProvider)\n\t\t\t  .setCredentialsProvider(credentialsProvider)\n              .build());\n\n      String formattedResource = TopicName.create(\"your-project\", \"saltopic2\").toString();\n\n      GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()\n        .setResource(formattedResource)\n        .build();\n      ApiFuture\u003cPolicy\u003e future = topicAdminClient.getIamPolicyCallable().futureCall(request);\n      Policy response = future.get();\n      System.out.println(response);\n\n```\n\n\n\n#### Cloud Go\n\nPackage [cloud.google.com/go/storage](https://godoc.org/cloud.google.com/go/storage)\n\n* [https://github.com/GoogleCloudPlatform/google-cloud-go](https://github.com/GoogleCloudPlatform/google-cloud-go)\n* [https://godoc.org/google.golang.org/api/storage/v1](https://godoc.org/google.golang.org/api/storage/v1)\n\nThe following shows google.DefaultTokenSource as well as gcloud's Application Default Credentials\n```golang\nimport (\n        \"golang.org/x/net/context\"\n        \"cloud.google.com/go/storage\"\n        \"google.golang.org/api/iterator\"\n        \"google.golang.org/api/option\"\n        \"log\"  \n)\n\n\tctx := context.Background()\n\t/*\n\t\ttokenSource, err := google.DefaultTokenSource(oauth2.NoContext, storage.ScopeReadOnly)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to acquire token source: %v\", err)\n\t\t}\n\t\tstoreageClient, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))\n\t*/\n\n\tstoreageClient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to acquire storage Client: %v\", err)\n\t}\n\n\tit := storeageClient.Buckets(ctx, \"your_project\")\n\tfor {\n\t\tbucketAttrs, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to acquire storage Client: %v\", err)\n\t\t}\n\t\tlog.Printf(bucketAttrs.Name)\n\t}\n\n```\n\n##### Adding custom headers\n\n```golang\npackage main\n\n\nimport (\n  \"context\"\n  \"io/ioutil\"\n  \"log\"\n  \"net/http\"\n\n  \"cloud.google.com/go/storage\"\n  \"google.golang.org/api/option\"\n  raw \"google.golang.org/api/storage/v1\"\n  htransport \"google.golang.org/api/transport/http\"\n)\n\nfunc main() {\n\n  ctx := context.Background()\n\n  // Standard way to initialize client:\n  // client, err := storage.NewClient(ctx)\n  // if err != nil {\n  //      // handle error\n  // }\n\n  // Instead, create a custom http.Client.\n  base := http.DefaultTransport\n  trans, err := htransport.NewTransport(ctx, base, option.WithScopes(raw.DevstorageFullControlScope),\n            option.WithUserAgent(\"custom-user-agent\"))\n  if err != nil {\n            // Handle error.\n  }\n  c := http.Client{Transport:trans}\n\n  // Add RoundTripper to the created HTTP client.\n  c.Transport = withDebugHeader{c.Transport}\n\n  // Supply this client to storage.NewClient\n  client, err := storage.NewClient(ctx, option.WithHTTPClient(\u0026c))\n  if err != nil {\n              // Handle error.\n  }\n\n  // Use client...\n }\n\ntype withDebugHeader struct {\n  rt http.RoundTripper\n}\n\nfunc (wdh withDebugHeader) RoundTrip(r *http.Request) (*http.Response, error) {\n  headerName := \"X-Custom-Header\"\n  r.Header.Add(headerName, \"value\")\n  resp, err := wdh.rt.RoundTrip(r)\n  if err == nil {\n    log.Printf(\"Resp Header: %+v, \", resp.Header.Get(headerName))\n  } else {\n    log.Printf(\"Error: %+v\", err)\n  }\n  return resp, err\n}\n```\n\n\n##### Exponential Backoff\n\nCloud libraries implement backoff automatically per service.\n\n- GCS\n  - [https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/storage/invoke.go#L26](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/storage/invoke.go#L26)\n\n- BQ\n  - [https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/bigquery/service.go#L705](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/bigquery/service.go#L705)\n  - [https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/bigquery/service.go#L529](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/bigquery/service.go#L529)\n\n\n#### Cloud Node\n\nThe _google-cloud_ node package initalizes the Cloud API library set:\n\n* [https://github.com/GoogleCloudPlatform/google-cloud-node](https://github.com/GoogleCloudPlatform/google-cloud-node)\n* [https://googlecloudplatform.github.io/google-cloud-node/#/](https://googlecloudplatform.github.io/google-cloud-node/#/)\n\nThe sample under [auth/compute/nodeapp](auth/compute/nodeapp) shows both Cloud APIs and Google APIs\n\n```node\nconst Storage = require('@google-cloud/storage');\nconst storage = new Storage({\n    projectId: 'your-project',\n  });\n\nstorage.getBuckets(function(err, buckets) {\n  if (!err) {\n  \tbuckets.forEach(function(value){\n  \t\t\tlogger.info(value.id);\n\t});\n  }\n});\n\nconst Pubsub = require('@google-cloud/pubsub');\nconst pubsub = Pubsub({\n    projectId: 'your-project'\n  });\n  pubsub.getTopics((err, topic) =\u003e {\n      if (err) {\n          logger.error(err);\n          return;\n      }\n      topic.forEach(function(entry) {\n      logger.info(entry.name);\n      });\n  });\n```\n\n#### Cloud C#\n\nUse [Google.Cloud.Storage.V1](https://www.nuget.org/packages/Google.Cloud.Storage.V1/) package for Google Cloud API access\n\n* [google-cloud-dotnet](https://github.com/GoogleCloudPlatform/google-cloud-dotnet)\n* [API Documentation](http://googlecloudplatform.github.io/google-cloud-dotnet/docs/Google.Cloud.Storage.V1/)\n\nSee [auth/service/dotnet](auth/service/dotnet) for sample for both Cloud APIs and Google APIs libraries.\n\n```csharp\nusing Google.Cloud.Storage.V1;\n\nnamespace CloudStorageAppGcloud\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var client = StorageClient.Create();\n\n            foreach (var obj in client.ListObjects(\"your_project\", \"\"))\n            {\n                Console.WriteLine(obj.Name);\n            }\n            Console.ReadLine();\n        }\n    }\n}\n\n```\n\n#### gRPC Environment Variables\n\n- [https://github.com/grpc/grpc/blob/master/doc/environment_variables.md](https://github.com/grpc/grpc/blob/master/doc/environment_variables.md)\n\n\n#### JWT Access Token\n\n-  - [auth/service/jwt_access_token](auth/service/jwt_access_token)\n\nJWT access tokens are efficient way to access certain google apis without the extra round trip to get an ```access_token```.  Unlike the normal Oauth service account flow where you\n1. use a local service account to sign a JWT,\n2. Exchange that JWT with google to get an ```access_token```\n3. Use that ```access_token``` to make an API call to google\n\nwith JWT Access Tokens, all you do is sign a JWT locally with a service account with the intended Service you want to access and then simply send it to the service.\n\nThe following links describes this flow:\n- [JWT Auth](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth)\n\nwhere these Google APIs will support this:\n- [https://github.com/googleapis/googleapis/tree/master/google](https://github.com/googleapis/googleapis/tree/master/google)\n\n\neg. for PubSub\n```golang\n\t// https://github.com/googleapis/googleapis/blob/master/google/pubsub/pubsub.yaml#L6\n\n\tctx := context.Background()\n\tprojectID := \"YOUR_PROJECT\"\n\tkeyfile := \"service_account.json\"\n\n\taudience := \"https://pubsub.googleapis.com/google.pubsub.v1.Publisher\"\n\n\tkeyBytes, err := ioutil.ReadFile(keyfile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to read service account key file  %v\", err)\n\t}\n\ttokenSource, err := google.JWTAccessTokenSourceFromJSON(keyBytes, audience)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error building JWT access token source: %v\", err)\n\t}\n\tjwt, err := tokenSource.Token()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to generate JWT token: %v\", err)\n\t}\n\tfmt.Println(jwt.AccessToken)\n\n\tpubsubClient, err := pubsub.NewClient(ctx, projectID, option.WithTokenSource(tokenSource))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create pubsub Client: %v\", err)\n\t}\n```\n\n#### Google API Client Library for Python\n\nThe following describes the older, non-idomatic libraries.  As you can see, its much easier using the idomatic library set.\n* [GCS JSON API](https://cloud.google.com/storage/docs/json_api/v1/buckets/list)\n\n```\nvirtualenv env\nsource env/bin/activate\npip install --upgrade requests google-api-python-client httplib2 oauth2client\n\n```\n\n```python\nimport os\nimport httplib2\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom oauth2client.client import GoogleCredentials\n\nscope='https://www.googleapis.com/auth/devstorage.read_only'\n\n#os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"YOUR_JSON_CERT.json\"\ncredentials = GoogleCredentials.get_application_default()\nif credentials.create_scoped_required():\n  credentials = credentials.create_scoped(scope)\nhttp = httplib2.Http()\ncredentials.authorize(http)\n\nservice = build(serviceName='storage', version= 'v1',http=http)\nresp = service.buckets().list(project='YOUR_PROJECT').execute()\nfor i in resp['items']:\n  print(i['name'])\n```\n\nYou can also initialize an `AuthorizedHttp` artifact from `google-auth` library with discovery:\n\n```python\n# http://google-auth.readthedocs.io/en/latest/reference/google.auth.html\n# https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2\nimport google.auth\nimport google_auth_httplib2\ncredentials, project = google.auth.default(scopes=scopes)\nhttp =  google_auth_httplib2.AuthorizedHttp(credentials)\n\nservice = build(serviceName='cloudtasks',\n  discoveryServiceUrl='https://cloudtasks.googleapis.com/%24discovery/rest?version=v2beta2',\n  version= 'v2beta2',http=http)\n```\n\n### Google API Python\n\n* [Google API Client Library for Python](https://developers.google.com/api-client-library/python/)\n\n```\napt-get install curl python2.7 python-pip\npip install requests google-api-python-client httplib2 oauth2client\n```\n\n#### ComputeEngine\n\nUnder [auth/compute/pyapp](auth/compute/pyapp)  Runs a simple application on compute engine using *Application Default Credentials*.\n\n\n```\ncd auth/compute/pyapp\nvirtualenv env\nsource env/bin/activate\npip install -r requirements.txt\n\npython compute.py\n```\n\n\n#### Service Account File\n\nUnder [auth/service/pyapp](auth/service/pyapp/)  Runs a simple application that uses the service account credential from both a PKCS12 file and a JSON keyfile.  Application Default Credentials uses the JSON keyfile only if the *GOOGLE_APPLICATION_CREDENTIALS* variable isset\n\nFor more details, goto [Service Accounts](https://developers.google.com/api-client-library/python/auth/service-accounts)\n\n#### Userflow\n\nUnder [auth/userflow/pyapp](auth/userflow/pyapp)  Runs a simple application that performs user-interactive webflow and propmpts the user for consent.  Download an *installed* app client_secrets.json and reference it for the 'flow_from_clientsecrets()' method.\n\nFor more deails, goto [flow_from_clientsecrets](https://developers.google.com/api-client-library/python/guide/aaa_oauth#flow_from_clientsecrets)\n\nThe sample also shows the simplified flow with a browser listener (so that you dont' have to type in the code manually):\n\n```python\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nflow = InstalledAppFlow.from_client_secrets_file(\n    'client_secrets.json',\n    scopes=['profile', 'email'])\n\nflow.run_local_server()\n\nclient = photos_v1.PhotoServiceClient(credentials=flow.credentials)\n```\n\n#### Misc\n\n##### Setting API Key\n\nExample showing how to set the [API_KEY](https://developers.google.com/api-client-library/python/guide/aaa_apikeys).\n```python\nservice = build(serviceName='oauth2', version= 'v2',http=http, developerKey='YOUR_API_KEY')\n```\n\n##### Logging\n\nEnable verbose wire tracing.\n```python\nimport logging\nimport httplib2\nimport sys\n\nlogFormatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')\nroot = logging.getLogger()\nroot.setLevel(logging.INFO)           \nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.INFO)    \nch.setFormatter(logFormatter)\nroot.addHandler(ch)\nlogging.getLogger('oauth2client.client').setLevel(logging.DEBUG)\nlogging.getLogger('apiclient.discovery').setLevel(logging.DEBUG)\n\nhttplib2.debuglevel=3\n```\n\n##### Credential store\n\nSee [credential store](https://developers.google.com/api-client-library/python/guide/aaa_oauth#storage) documentation.\n\n\n##### ID Token from Service Account JSON Signed by Google\n\nIf you need an id_token issued by Google using your JSON certificate:\n\nTHe old way was to run through the full flow _manually_:\n\n```python\nfrom oauth2client.service_account import ServiceAccountCredentials\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('YOUR_SERVICE_AcCOUNT.json')\nnow = int(time.time())\npayload = {\n        'iat': now,\n        'exp': now + credentials.MAX_TOKEN_LIFETIME_SECS,\n        'aud': 'https://www.googleapis.com/oauth2/v4/token',\n        'iss': 'svc1-001@YOUR_PROJECT.iam.gserviceaccount.com',\n        'scope': 'svc1-001@YOUR_PROJECT.iam.gserviceaccount.com'\n}\nsigned_jwt = oauth2client.crypt.make_signed_jwt(credentials._signer, payload, key_id=credentials._private_key_id)\nparams = urllib.urlencode({\n      'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n      'assertion': signed_jwt })\nheaders = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\nconn = httplib.HTTPSConnection(\"www.googleapis.com\")\nconn.request(\"POST\", \"/oauth2/v4/token\", params, headers)\nres = json.loads(conn.getresponse().read())\nprint(res)\n```\n\nThe new (preferred) way is to use the new ```iamcredentials`` API directly.  See [id_tokens/README.md](id_tokens/README.md)\n\n- [id_tokens/iam_svc_tokens/main.py](id_tokens/iam_svc_tokens/main.py).  \n\n\nboth which Returns JSON with a JWT signed by Google:\n\n```json\n{\"id_token\": \"YOUR_ID_TOKEN_SIGNED_BY_GOOGLE\"}\n\n```\nDecoded JWT id_token:\n```json\n{\n  \"iss\": \"https://accounts.google.com\",\n  \"aud\": \"svc1-001@YOUR_PROJECT.iam.gserviceaccount.com\",\n  \"sub\": \"111402810199779215722\",\n  \"email_verified\": true,\n  \"azp\": \"svc1-001@YOUR_PROJECT.iam.gserviceaccount.com\",\n  \"email\": \"svc1-001@YOUR_PROJECT.iam.gserviceaccount.com\",\n  \"iat\": 1468897846,\n  \"exp\": 1468901446\n}\n```\n\nIf you are running the flow directly, if you used *'scope': 'https://www.googleapis.com/auth/userinfo.email'*, the return fields would include an access_token scoped to userinfo.email for the service account.  \n\n***  \n\n### Google API Java\n\n[Java API Client Library](https://developers.google.com/api-client-library/java/).  Most of the samples below uses gradle to build and deploy.\n\n\n#### ComputeEngine\n\nUnder [auth/compute/javaapp](auth/compute/javaapp).  Runs a simple application using both *Application DefaultCredentials* and *ComputeCredential*.\n\n\n```bash\nmvn exec:java\n```\n#### Service Account File\n\nUnder [auth/service/javaapp](auth/service/javaapp).  Runs a simple application using both *Application DefaultCredentials* and by directly reading in the JSON certificate file.  If the *GOOGLE_APPLICATION_CREDENTIALS* variable is set to point to the JSON file, the applicationDefault profile will also read the JSON file (otherwise, it will attempt to pick up the gcloud credentials)\n\n\n```bash\nmvn exec:java\n```\n#### UserFlow\n\nUnder [auth/userflow/javaapp](auth/userflow/javaapp).  Runs a simple webflow application to acquire user consent for GoogleAPIs.  This particular userflow launches a browser and listener.\n\n```bash\nmvn exec:java\n```\n#### Misc\n\n##### Logging\n\n```java\nimport java.util.logging.ConsoleHandler;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.logging.SimpleFormatter;\n\nConsoleHandler consoleHandler = new ConsoleHandler();\nconsoleHandler.setLevel(Level.ALL);\nconsoleHandler.setFormatter(new SimpleFormatter());\n\nLogger logger = Logger.getLogger(\"com.google.api.client\");\nlogger.setLevel(Level.ALL);\nlogger.addHandler(consoleHandler);  \n\nLogger lh = Logger.getLogger(\"httpclient.wire.header\");\nlh.setLevel(Level.ALL);\nlh.addHandler(consoleHandler);\n\nLogger lc = Logger.getLogger(\"httpclient.wire.content\");\nlc.setLevel(Level.ALL);\nlc.addHandler(consoleHandler);\n\nLogger gl = Logger.getLogger(\"io.grpc\");\ngl.setLevel(Level.FINE);\ngl.addHandler(consoleHandler);\n```\n\n##### Setting API Key\n\n```java\nString API_KEY = \"...\";\nOauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)\n    .setApplicationName(\"oauth client\")\n    .setOauth2RequestInitializer(new Oauth2RequestInitializer(API_KEY))    \n    .build();\n```\n\n##### Setting Request Parameter\n\n```java\nOauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)\n    .setApplicationName(\"oauth client\")\n    .setOauth2RequestInitializer(new Oauth2RequestInitializer(){\n        @Override\n        public void initializeOauth2Request(Oauth2Request\u003c?\u003e request) {\n            request.setPrettyPrint(true);\n        }\n    })      \n    .build();\n```\n\n##### Credential store\n\nSee documentatin on [Drive](https://developers.google.com/drive/web/credentials?hl=en)\n\n\n##### Exponential Backoff\n\nSee [ExponentialBackOff](https://developers.google.com/api-client-library/java/google-http-java-client/backoff)\n\n\nUsign GoogleAPIs:\n\n```java\nimport com.google.api.client.util.ExponentialBackOff;\n\nfinal GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory).createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));\n\nOauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() {\n                public void initialize(HttpRequest request) throws IOException {\n                    request.setContentLoggingLimit(0);\n                    request.setCurlLoggingEnabled(false);\n                    credential.initialize(request);\n                    ExponentialBackOff backoff = new ExponentialBackOff.Builder()\n                    .setInitialIntervalMillis(500)\n                    .setMaxElapsedTimeMillis(900000)\n                    .setMaxIntervalMillis(6000)\n                    .setMultiplier(1.5)\n                    .setRandomizationFactor(0.5)\n                    .build();\n                  request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));\n                }\n            })                  \n            .setApplicationName(\"oauth client\")\n            .build();\n```\n\nor using Cloud Libraries\n\n```java\nimport com.google.api.gax.retrying.RetrySettings;\n\n        Storage storage = StorageOptions.newBuilder()\n            .setCredentials(myprovider.getCredentials())\n            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())\n            .build()\n            .getService();\n```\n\n***  \n\n###  Google API Go\n[DefaultTokenSource](https://godoc.org/golang.org/x/oauth2/google#DefaultTokenSource)  \n\n\n#### ComputeEngine\n\nUnder [auth/compute/goapp](auth/compute/goapp).  Runs a simple application using both *Application DefaultCredentials* and *ComputeTokenSource*.  To deploy:\n\n\u003e Make sure you create a GCE instance with the ```userinfo.email``` scope.  That will allow the token to be used against the oauth2 endpoint\n\n```bash\nexport GOPATH=`pwd`\n\ngo get golang.org/x/oauth2\ngo get google.golang.org/cloud/compute/...\ngo get google.golang.org/api/oauth2/v2\ngo get cloud.google.com/go/compute/metadata\n\n\ngo run src/main.go\n```\n\n#### Service Account JSON File\n\nUnder [auth/service/goapp](auth/service/goapp).  Runs a simple application using both *Application DefaultCredentials* and directly reading *JWTConfigFromJSON*.  \n\nThe sample also demonstrates _both_ google api clients and google cloud client libraries.\n\nTo use:\n\nedit\n```\tserviceAccountJSONFile := \"YOUR_SERVICE_ACCOUNT_JSON_FILE\"```   and set the path to your service account JSON file.\nAfter that, you can either explictly use the credential type for service account (```JWTConfigFromJSON```, or set the environment variable ause ADC)\n\nTHis sample also uses the service account to iterate over the Cloud Storage buckets.  Make sure the service account has that permissoin\n\n```bash\nexport GOPATH=`pwd`\n\ngo get golang.org/x/oauth2\ngo get google.golang.org/cloud/compute/...\ngo get google.golang.org/api/oauth2/v2\ngo get cloud.google.com/go/compute/metadata\ngo get github.com/googleapis/gax-go\ngo get o.opencensus.io/trace\ngo get go.opencensus.io/plugin/ochttp\ngo get go.opencensus.io/exporter/stackdriver/propagation\ngo get google.golang.org/grpc\n\ngo run src/main.go\n```\n\n#### UserFlow\n\nUnder [auth/userflow/goapp](auth/userflow/goapp).   Runs a simple webflow application to acquire user consent for GoogleAPIs.  This particular userflow launches a link URL and expects the authorization token to get entered (installed application).\n\nTo use, go to the cloud console, \"API \u0026 Credentials \u003e Credentials\", then \"Create Credentials \u003e Oauth2 Credentials \u003e Other\".  Copy the clientID and secret into main.go:\n\n```\n        ClientID:     \"YOUR_CLIENT_ID\",\n        ClientSecret: \"YOUR_CLIENT_SECRET\",\n```\n\n```bash\ngo get golang.org/x/net/context\ngo get golang.org/x/oauth2/google\ngo get google.golang.org/cloud/compute/...\ngo get google.golang.org/api/oauth2/v2\n\ngo run src/main.go\n```\n\nYou will see a URL.  Copy that URL to a browser, login and then enter the code.  This sample runs the \"installed application\" flow\n\n#### Misc\n\n##### Setting API Key\n\n```go\nimport \"google.golang.org/api/googleapi/transport\"\napiKey :=\"YOUR_API_KEY\"\nclient.Transport = \u0026transport.APIKey{\n    Key: apiKey,\n}\n```\n\n##### ID Token Signed by Google\n\nsee\n- [https://github.com/salrashid123/google_id_token](https://github.com/salrashid123/google_id_token)\n- [https://github.com/salrashid123/grpc_google_id_tokens](https://github.com/salrashid123/grpc_google_id_tokens)\n\n\n- [id_token/README.md](id_token/README.md)\n\n[Validating id_token](https://developers.google.com/identity/protocols/OpenIDConnect?hl=en#validatinganidtoken)\n\n\nAlso see  \n* [Golang Token verificaiton](http://stackoverflow.com/questions/26159658/golang-token-validation-error/26287613#26287613)\n* [JWT debugger](http://jwt.io/)\n\n##### Credential store\n\nSee [oauth2.ReuseTokenSource](https://www.godoc.org/golang.org/x/oauth2#ReuseTokenSource)\n\n```go\n\nsrc, err := google.DefaultTokenSource(oauth2.NoContext, oauthsvc.UserinfoEmailScope)\nif err != nil {\n   log.Fatalf(\"Unable to acquire token source: %v\", err)\n}\n\ntok, err := tokenFromFile(\"credential.token\")\nsrc = oauth2.ReuseTokenSource(tok,src)\ntokenval, err := src2.Token()\nif err != nil {\n    log.Fatalf(\"Token can't be read\")\n} else {\n    log.Printf(\"token %v\\n\", tokenval.AccessToken)\n}\n\nclient := oauth2.NewClient(context.Background(), src)\nsvc, err := oauthsvc.New(client)\nif err != nil {\n    log.Fatalf(\"ERROR: \", err)\n}\n...\n...\nfunc saveToken(file string, token *oauth2.Token) {\n    f, err := os.Create(file)\n    if err != nil {\n        log.Printf(\"Warning: failed to cache oauth token: %v\", err)\n        return\n    }\n    defer f.Close()\n    json.NewEncoder(f).Encode(token)\n}\n\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\n    f, err := os.Open(file)\n    if err != nil {\n        return nil, err\n    }\n    defer f.Close()\n    t := new(oauth2.Token)\n    err = json.NewDecoder(f).Decode(t)\n    return t, err\n}\n```\n\n##### Logging\n\nThe follwoing example of trace http logging wraps the Transport around a logging version:\n[LogTransport](https://code.google.com/p/google-api-go-client/source/browse/examples/debug.go).  \n\nThis example also shows how the *API_KEY* could get constructed although this particular API (oauth2/v2) does not need or expect an api_key.\n\n```go\npackage main\nimport (\n    \"golang.org/x/oauth2\"\n    \"golang.org/x/oauth2/google\"    \n    \"log\"   \n    oauthsvc \"google.golang.org/api/oauth2/v2\"\n    \"google.golang.org/api/googleapi/transport\"\n    \"net/http\"\n)\nconst (\n    api_key   = \"YOUR_API_KEY\"\n)\nfunc Auth() {\n    src, err := google.DefaultTokenSource(oauth2.NoContext, oauthsvc.UserinfoEmailScope)\n    if err != nil {\n        log.Fatalf(\"Unable to acquire token source: %v\", err)\n    }\n    transport := \u0026transport.APIKey{\n    //  Key:       api_key,\n        Transport: \u0026logTransport{http.DefaultTransport},\n    }\n    client := \u0026http.Client{\n        Transport: \u0026oauth2.Transport{\n            Source: src,\n            Base:   transport,\n        },\n    }           \n    service, err := oauthsvc.New(client)\n    if err != nil {\n        log.Fatalf(\"Unable to create oauth2 service client: %v\", err)\n    }\n    ui, err := service.Userinfo.Get().Do()\n    if err != nil {\n        log.Fatalf(\"ERROR: \", err)\n    }   \n    log.Printf(\"UserInfo: %v\", ui.Email)\n}\n```\n\n\n***  \n\n###  Google API NodeJS\n[google.auth.getApplicationDefault](https://developers.google.com/identity/protocols/application-default-credentials#callingnode)  \n\n#### ComputeEngine\n\nRuns sample on ComputeEngine.  Requires the userinfo scope enabled on the compute engine instance.\n\n```bash\nnpm install\nnpm start\n```\n\n#### Service Account JSON File\n\nUnder [auth/service/nodeapp](auth/service/nodeapp).  Runs a simple application using both *Application DefaultCredentials* and directly reading *JSON KEY file*.\n\n#### UserFlow\n\nUnder [auth/userflow/nodeapp](auth/userflow/nodeapp).   Runs a simple webflow application to acquire user consent for GoogleAPIs.  This particular userflow provides a link URL and expects the authorization token to get entered (installed application).\n\n\n#### Misc\n\n##### Setting API Key\n\n```node\nvar service = google.oauth2({\n      version: 'v2',\n      auth: authClient,\n      params: { key: 'YOUR_API_KEY'}\n});\n```\n\n##### Logging\n\n```bash\nexport NODE_DEBUG=request\n```\n\n***\n\n###  Google API C\u0026#35;\n.NET packages downloadable from [NuGet](https://www.nuget.org/packages/Google.Apis/).  Full end-to-end example of all the auth modes available here for CloudStorage\n\n* [Google API .NET Library](https://developers.google.com/api-client-library/dotnet/get_started)\n\n\nThe following code snippet demonstrates *both* google apis and google cloud libraries all in one [auth/compute/dotnet](auth/compute/dotnet):\n\n```\ncd auth/compute/dotnet\ndotnet restore\ndotnet run\n```\n\n\n#### Appengine\n\nGAE Standard does not support .NET as a runtime.  However, you can deploy your application to GAE Flex if you run .NET Core on Linux.  See the following sample that runs a .NET\nwebapp in Flex:  [.NET on GCP](https://github.com/salrashid123/gcpdotnet).\nNote: Google APIs do not support .NET Core (coreCLR) yet.  At the time of writing, they only supports upto [.NET Framework 4.5.1](https://www.nuget.org/packages/Google.Apis/).  This\nmeans you cannot use Google APIs from within a Container.   There are some [ports](https://www.nuget.org/packages/GoogleApis.Core.vNext/) to coreCLR but they are not officially supported.\n\n#### ComputeEngine\n\nUnder [auth/compute/dotnet](auth/compute/dotnet).  Runs a simple application using both *Application DefaultCredentials* and *ComputeCredential*.\n\n```\ndotnet restore\ndotnet run\n```\n\n#### Service Account JSON File\n\nUnder [auth/service/dotnet](auth/service/dotnet).  Runs a simple application using both *Application DefaultCredentials* using a **JSON Certificate** and by directly reading in the **PKCS12 Certificate** file.  If the *GOOGLE_APPLICATION_CREDENTIALS* variable is set to point to the **JSON file**, the applicationDefault profile will also read the JSON file (otherwise, it will attempt to pick up the gcloud credentials).\n\nEdit [service/dotnet/ServiceAuth.cs](service/dotnet/ServiceAuth.cs) file and set the path to the service account key file.  Then,\n\n```\ndotnet restore\ndotnet run\n```\n\n#### UserFlow\n\nUnder [auth/userflow/dotnet](auth/userflow/dotnet).   Runs a simple webflow application to acquire user consent for GoogleAPIs.  This particular userflow launches provides a link URL and expects user consent on the browser.\n\n##### Credential store\n\nCredentials from the GoogleAPIs userflow is usually stored at\n\n```\nEnvironment.GetFolderPath(Environment.SpecialFolder.ApplicationData));\nor c:\\Users\\%USER%\\AppData\\Roaming\\Google.Apis.Auth\n```\n\n#### Using API through Proxy\n\ngRPC clients support http_proxy parameter:\n- [https://github.com/grpc/grpc/blob/master/doc/environment_variables.md](https://github.com/grpc/grpc/blob/master/doc/environment_variables.md)\n\n\n* The following is curated from:\n[https://kzhendev.wordpress.com/2015/04/28/accessing-google-apis-through-a-proxy-with-net/](https://kzhendev.wordpress.com/2015/04/28/accessing-google-apis-through-a-proxy-with-net/)\n\n\nSee [proxy](proxy) folder for detailed usage.\n\nto use:\n\n```\ndocker run  -p 3128:3128 -ti docker.io/salrashid123/squidproxy /bin/bash\n\nthen when inside the container:\n/apps/squid/sbin/squid -NsY -f /apps/squid.conf.transparent \u0026\n\ntail -f /apps/squid/var/logs/access.log\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsalrashid123%2Fgcpsamples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsalrashid123%2Fgcpsamples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsalrashid123%2Fgcpsamples/lists"}