Quantcast
Channel: C# – Falafel Software Blog
Viewing all articles
Browse latest Browse all 54

Pub/Sub Part 1 : C# OAuth Authentication to Google Cloud Pub/Sub using a Service Account

$
0
0
If you are looking to consume Google Cloud services, you will need to authenticate. In my case, I was looking to use a service account created for a Pub/Sub application that I have in mind. I will walk you through creating a Service Account, downloading a key and authenticating with the Google Cloud Platform using a C# library.
The first thing that you will need to do is log into the Google Cloud Platform console (create a project, if you don’t already have one). From the hamburger menu in the top left, select IAM & Admin.
Google Cloud Platform IAM & Admin

Google Cloud Platform IAM & Admin

From there, select Service Accounts, then click the button to create a new Service account.
Google Cloud Platform Create Service Account

Google Cloud Platform Create Service Account

In the Create Service Account form, you’ll need to give the account a meaningful name, as well as assign it to one or more roles. In my case, my service account will need the Pub/Sub editor role. Make note of the service account id email address. Then click the checkbox to furnish a private key, and select the P12 key. Once you are finished, press the Create button, and the private key’s password will be displayed (it will be notasecret), and a download of the P12 key will begin.
Google Cloud Platform Service Account Creation Form

Google Cloud Platform Service Account Creation Form

Now we are ready to fire up Visual Studio. In this example, we will create a simple console application. I’ve named my project GcpOAuthConsole.
New Visual Studio Project

New Visual Studio Project

The first thing that is required is to add the Google.Api.Auth package via NuGet to the project.
Adding the Google.Apis.Auth NuGet Package

Adding the Google.Apis.Auth NuGet Package

Next we’ll add the P12 key file that we downloaded from the Google Cloud Platform console to the project, be sure to set the build action to content, and to Copy Always to the output directory.
Including the Service Account P12 Key in Visual Studio

Including the Service Account P12 Key in Visual Studio

Google authentication uses Scopes to identify the service(s) that an account is authenticating to. Find a listing of available scopes here. In my case, I want to authenticate to Google Cloud Pub/Sub API services. My scope will be one of either https://www.googleapis.com/auth/cloud-platform OR https://www.googleapis.com/auth/pubsub . In this example I’ll use the latter, though either will work.
Google Authentication Scopes for Pub/Sub

Google Authentication Scopes for Pub/Sub

Let’s dive into some code. Below is a code listing that will authenticate to Google using the P12 key, and receive in return an OAuth token that can be used in subsequent calls to the Google Cloud Platform. Also make note that I’ve included code to identify if the OAuth token is expired based on the Clock provided by the ServiceAccountCredential object. Add the following using statements to your Program.cs file:
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
Finally, include the following code within the Main method of your console application:
Console.WriteLine("Google Cloud Service Account using OAuth Example");

string p12CertificatePath = "CSharpPubSub-c07c67be2080.p12";
string serviceAccountEmail = "oauth-to-gcp-sample@csharppubsub.iam.gserviceaccount.com";
var certificate = new X509Certificate2(p12CertificatePath, "notasecret", X509KeyStorageFlags.Exportable);

var credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new[] { "https://www.googleapis.com/auth/pubsub" }
        }.FromCertificate(certificate));

credential.RequestAccessTokenAsync(CancellationToken.None).Wait();

Console.WriteLine($"OAuth Token Obtained: {credential.Token.AccessToken}");
Console.WriteLine($"Is OAuth Token Expired ?: {credential.Token.IsExpired(credential.Clock)}");

Console.ReadLine();
Getting an OAuth Token from Google

Getting an OAuth Token from Google

Now that we have an OAuth token, we have the ability to call into Pub/Sub related API calls (defined by our scope(s)). Use this token as a Bearer token in the Authorization header of your http calls, as shown below:

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credential.Token.AccessToken);
Here is a helper class that encapsulates the functionality that we’ve just reviewed:
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;

namespace FalafelDev
{
    public class GCP_OAuth_ServiceCredential
    {
        public ServiceCredential Credential { get; }

        public GCP_OAuth_ServiceCredential(string serviceAccountEmail, string p12CertificatePath, List<string> scopes)
        {
            var certificate = new X509Certificate2(p12CertificatePath, "notasecret", X509KeyStorageFlags.Exportable);
            Credential = new ServiceAccountCredential(
                 new ServiceAccountCredential.Initializer(serviceAccountEmail)
                 {
                     Scopes = scopes 
                 }.FromCertificate(certificate));
        }

        public async Task<HttpClient> GetHttpClient()
        {
            bool hasToken = false;

            if (Credential.Token == null || Credential.Token.IsExpired(Credential.Clock))
            {
                hasToken = await Credential.RequestAccessTokenAsync(CancellationToken.None);
            }
            else
            {
                hasToken = true;
            }
            if (hasToken)
            {
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 
                       Credential.Token.AccessToken);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return httpClient;
            }

            return null;

        }
    }
}
 

The post Pub/Sub Part 1 : C# OAuth Authentication to Google Cloud Pub/Sub using a Service Account appeared first on Falafel Software Blog.


Viewing all articles
Browse latest Browse all 54

Trending Articles