Google Analytics API error 403: “User does not hav

2019-02-26 06:04发布

问题:

I've been trying to learn how to use the Google Analytics API to get site traffic data. I keep running into an error saying that the user does not have permission to access the profile. I added the email address from the service account to the users and tried making it both a user with access to all profiles and an administrator and neither worked.

This is my code, which I got from here:

        string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();
        string clientId = "xxxxxxxx@developer.gserviceaccount.com";
        string keyFile = @"C:\Users\emorris\Downloads\xxxxxxxxxx-privatekey.p12";
        string keyPassword = "notasecret";

        AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

        X509Certificate2 key = new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable);

        AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId= clientId, Scope = scope };

        OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

        AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });

        DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:xxxxxx", "2013-05-01", "2013-05-31", "ga:visitors");

        GaData d = r.Fetch();

It runs into the problem at the last line, where it gives me:

Google.Apis.Requests.RequestError

User does not have sufficient permissions for this profile. [403]

I looked here where there seemed to be a similar problem but all it says is to add the email as a user in the APIs console, which I did. Anyone know what I need to change?

回答1:

Just to confirm -- in the original post, you said you added the email in "APIs console". But you actually need to add the email to your Google Analytics Profile using the Analytics web UI. Did you do that? This error occurs only if the user id you're making the request with is not on the analytics profile.