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:
- Access to the Smart Home account in the GCP console
- Add a Service account of type
service account token creator
- Download the private key of the service account (a JSON file)
- 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
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:
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!