3

I have a desktop Java app that I am migrating from Google Contacts API to People API. I have some of it working. For example, I can retrieve contact information. But when I tried to create a new contact, I get the following error:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
POST https://people.googleapis.com/v1/people:createContact
{
  "code" : 403,
  "details" : [ {
   "@type" : "type.googleapis.com/google.rpc.ErrorInfo",
   "reason" : "ACCESS_TOKEN_SCOPE_INSUFFICIENT"
  } ],
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Request had insufficient authentication scopes.",
  "status" : "PERMISSION_DENIED"
}

Here's the relevant code:

protected void createContact() throws Exception {
    
    Credential credential = authorize(PeopleServiceScopes.CONTACTS, "people");
    
    PeopleService service = new PeopleService.Builder(
              httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

    
    Person contactToCreate = new Person();
    List<Name> names = new ArrayList<Name>();
    names.add(new Name().setGivenName("John").setFamilyName("Doe"));
    contactToCreate.setNames(names);

    Person createdContact = service.people().createContact(contactToCreate).execute();
    System.out.println("CREATED Contact: " + createdContact.getNames().get(0).getDisplayName());
}

protected Credential authorize(String scope, String subDir) throws Exception {
    
    File dataStoreDir = new File(System.getProperty("user.home"), ".store/myapp/" + cfg.dataStore + "/" + subDir);
    
    // initialize the transport
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    // initialize the data store factory
    dataStoreFactory = new FileDataStoreFactory(dataStoreDir);
    
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(SyncMgr.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
                + "into /client_secrets.json");
        System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets,
            Collections.singleton(scope)).setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(cfg.gUser);
}

When I first ran it, I had the scope set to CONTACTS_READONLY. And I got the consent screen. But then I changed the scope to CONTACTS when I added the code to create a new contact. And that's when I got the ACCESS_TOKEN_SCOPE_INSUFFICIENT error.

I saw in another post that I need to force your app to reauthorize the user when you change the scope, so that you get the consent screen again. But I'm not sure how to do that. Any suggestions?

Thanks.

UPDATE 1/4/22

I tried Gabriel's suggestion of removing access to the application. After removing access, I ran the application again. This time I got this error on the execute() call:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
POST https://oauth2.googleapis.com/token
{
  "error" : "invalid_grant",
  "error_description" : "Token has been expired or revoked."
}

And even the execute() statement that worked before to retrieve contacts is giving the same error now.

My application also used the Calendar API. I didn't touch that code. But when I try to use it, I get the same "invalid_grant" error. What do I do now?

Eric S
  • 133
  • 1
  • 9

2 Answers2

3

You appear to be using the People.createContact method. If we take a look at the documentation we will see that this method requires a consent to the following scope of permissions from the user

enter image description here

Now if we check your code you apear to be using

Credential credential = authorize(PeopleServiceScopes.CONTACTS, "people");

Which is the exact scope needed. But you oringally had readonly there. So when your code ran the first time the user authorized to the read only scope and not the full contacts scope and your stuck.

The key here is this section of code.

// set up authorization code flow
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(scope)).setDataStoreFactory(dataStoreFactory).build();
// authorize
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(cfg.gUser);

Kindly note I am not a Java developer I am a .net developer. The libraries are very close and i have been helping with questions this in both languages for years.

dataStoreFactory is where the consent from the user is stored. There should be a json file some where in your directory structure with the users name associated with it this is how your system reloads it. When your code runs it will look for a file in that directory with cfg.gUser name.

There should be a way in the Java client library to force it to rerequest authorization of the user. prompt type force. But i will have to look around to see how to do it in java.

The easiest solution now would be to find that directory and delete the file for the user or just change the users name cfg.gUser to cfg.gUser +"test" or something this will cause the name to change and the file name as well. Forcing it to prompt the user for authorization again.

This time when it requests consent take note which scope of permissions it asks for.

Token has been expired or revoked.

This is probably due to the fact that your refresh tokens are expiring. When your application is in the testing phase the refresh tokens are expired or revoked automatically by google after seven days.

This is something new and something that Google added in the last year or so. Unfortunately the client libraries were not designed to request access again if the refresh token was expired in this manner.

enter image description here

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • @DalmTo Thank you! I found the data store directory and renamed that json file. When I ran the application again, I got the consent screen. Now, everything is working again. Thanks again for the great explanation! – Eric S Jan 05 '22 at 16:14
  • Remember to accept the answer if it helps. – Linda Lawton - DaImTo Jan 05 '22 at 17:29
1

If you are looking to retrieve the consent screen again you can remove access to your application from your account settings by following the steps in this documentation and then try to authorize the app again. As you mentioned, the error received is due to the scope that was granted with authorization was CONTACTS_READONLY instead of CONTACTS when checking the authorization scope for this specific create contacts method.

Gabriel Carballo
  • 1,278
  • 1
  • 3
  • 9
  • I guess I can try that. Although I do want the application to ultimately have access to my account. Do I remove it, and then add it back again right away? Or will it get added back when I try to run the application again and I get the consent screen? – Eric S Jan 03 '22 at 20:03
  • When you try to run the application again after removing it you will be presented with the consent screen, once you provide access it should be added back again to your account as a third party app with account access. – Gabriel Carballo Jan 03 '22 at 20:15
  • Well, that didn't work. See update in my question above. – Eric S Jan 04 '22 at 14:19
  • 1
    Checking that the new error message that you receive seems to be related to a Refresh token, I found a similar issue in this thread and you may try one of the solutions listed: https://stackoverflow.com/questions/66240374/token-has-expired-or-revoked-google-ads – Gabriel Carballo Jan 04 '22 at 15:41
  • Thanks. I tried a couple of those solutions and one worked. I deleted the StoredCredential file and re-ran the application. This time, I got the consent screen and approved it, and the application ran without errors. – Eric S Jan 05 '22 at 02:05
  • Thanks for your answer, it worked. It is just sad how this whole OAuth2 mechanism on GCP heavily relies on stackoverflow – downvoteit Jul 23 '23 at 19:47