Search code examples
pythonazure-functionsgoogle-analytics-api

How can I securely store a Google Analytics GA4 credentials.json file in Azure Functions?


I'm creating an Azure Function in Python using the google-analytics-data client library to download google analytics data every month. The instructions on https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries require the API credentials to exist locally in a file called credentials.json. When I deploy that to Azure Functions, will that exist in plain text? Is there any way to encrypt it?

Seems like I should be able to pass parameters in BetaAnalyticsDataClient() instead of using a file, but https://googleapis.dev/python/analyticsdata/latest/data_v1beta/beta_analytics_data.html looks like it wants a token from an OAuth handshake, not the credentials in credentials.json.

What I've found so far in my research:

It's not a must to use the google-analytics-data client library, just seems like it would be a lot easier. What's the best way to securely authenticate with the GA4 API from Azure Functions?


Solution

  • Thank you for your comments, @SiddheshDesai! Your answer turns out to be half of the solution. Step 1 is to store the entire contents of credentials.json as a single variable in local.settings.json or Azure key vault. Step 2, as documented on https://googleapis.dev/python/google-auth/latest/user-guide.html#service-account-private-key-files, is to use service_account.Credentials.from_service_account_info to generate a Credentials object that can be passed to BetaAnalyticsDataClient. My local.settings.json looks like this:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "python",    
        "ga4_credentials_json": "{\"type\": \"service_account\",\"project_id\": \" <etc...>
      }
    }  
    

    And here's my working code to declare the client:

        json_acct_info = json.loads(os.getenv('ga4_credentials_json'))
        credentials = service_account.Credentials.from_service_account_info(
            json_acct_info)
        scoped_credentials = credentials.with_scopes(
            ['https://www.googleapis.com/auth/analytics.readonly'])
    
        client = BetaAnalyticsDataClient(credentials=scoped_credentials)
    

    Then you just define your request and response = client.run_report(request) ! Life is good.