Sign a Google API JWT in .net C#

In a Google Smart Home project I needed my .net core server application to call the Report State API. The call needs to be authorized by an OAUTH 2.0 access token.

There are many steps to perform on the Google Cloud Platform console (GCP) to obtain this token:

  1. Access to the Smart Home account in the GCP console
  2. Add a Service account of type service account token creator
  3. Download the private key of the service account (a JSON file)
  4. Enable the API you want to call

Then in the .net application you need to:

  • Craft a JWT for the request
  • Sign the JWT with the service account JSON private key
  • Call the Google OAUTH 2 service to get the access token
  • Use the fresh access token to call the API

Let’s begin!

1- Create/select the GCP account (the right one!)

WARNING: this first step can be tricky!

The GCP console contains all of your projects. And it should contains also the project related to the Google Smart Home action. To be sure to select the right GCP project go in the Actions console, select the action you are working on, and click on the upper right menu, then click Manage user access on Google Cloud Platform.

You will be redirected to the IAM page of the relative GCP account, with all the resource listed. Click on Service Account:

2- Add a service account

The service account is needed in the machine-to-machine flow, exactly when our .net server application call the Report State API. We need to create a service account and give it the Service Account Token Creator role:

3-The JSON private key

Click on ‘Create Key‘ to download the JSON private key file:

Select the JSON file type:

Keep safe the JSON file.

4-Enable the Report State API for this GCP account

To call the API it must be granted. In the GCP dashboard click the API arrow:

Add the HomeGraph API:

.net application

The official Google guide is here. This tutorial is for a .net project that needs to call the Report State API:

There is a little-to-none documented .net library for the HomeGraph API available via nuget: Google.Apis.HomeGraphService.v1.

With this library is possible to create the JWT, sign it with the secret key directly from its JSON file, ask for access token and call the ReportState API in just one call!

2 replies on “Sign a Google API JWT in .net C#”

Hi! I’ve been looking for this for a while, and your article was of great help. I had no problem creating the fulfillment service, but the “opposite direction” (i.e. request sync and report state the the HomeGraph API) was something that I didn’t know how to address from C#. Your code worked like a charm, and now I’m almost ready for the submission process, in great mesure thanks tou you.


Glad this helped, it took me a while to get this work in .net!

Leave a Reply

Your email address will not be published. Required fields are marked *