Google .NET API fails due to error 403 (forbidden)

2019-09-13 06:03发布

问题:

My code snippet below is supposed to return the list of beacons. When having Google API Console generate an API Key I have whitelisted my public IP address and associated with the api key. When the code calls ExecuteAsync() method, I keep receiving an exception with error code 403 (forbidden). What may have I done wrong and how to mitigate the issue?

public async void TestApiKey()
{
    var apikey = "739479874ABCDEFGH123456"; //it's not the real key I'm using
    var beaconServices = new ProximitybeaconService(new Google.Apis.Services.BaseClientService.Initializer
    {
        ApplicationName = "My Project",
        ApiKey = apikey
    });

    var result = await beaconServices.Beacons.List().ExecuteAsync();

    // Display the results.
    if (result.Beacons != null)
    {
        foreach (var api in result.Beacons)
        {
            Console.WriteLine(api.BeaconName + " - " + api.Status);
        }
    }
}

回答1:

You are using a Public API key. Public API keys only work with public data.

beacons.list Authenticate using an OAuth access token from a signed-in user with viewer, Is owner or Can edit permissions.

Requires the following OAuth scope:
•https://www.googleapis.com/auth/userlocation.beacon.registry

The method you are trying to access is accessing private user data. You need to be authentication before you can use it. Switch to Oauth2 authentication. Setting it to public probably wont work because you cant to my knowledge supply a scope to a public api key.