Search code examples
javaoauthpermissionsgoogle-drive-realtime-api

Google Drive API Change Ownership oAuth


I have created an oAuth2 Google Drive application and am creating new files under the developer.gserviceaccount.com service account. I would like to change ownership to another account in the domain who owns this service account.

I have the file id of the newly created file and the permission id of the user I'd like to transfer ownership to, however when I run:

File body;
File file;

body = new File();
body.setTitle(gdf.getTitle());
body.setDescription(gdf.getDescription());            
body.setMimeType(gdf.getMime_type());
body.setUserPermission(p);

// new file gets created ok
file = d.files().insert(body).execute();  

// create new permission for new user account
Permission p = new Permission();
p.setRole("owner");
p.setType("user");
p.setValue("[email protected]");
p.setId(ACCESS_DOMAIN_PERMISSION_ID);  // <-- known value

d.permissions().update(file.getId(), ACCESS_DOMAIN_PERMISSION_ID, p).execute();

The statement fails complaining about not being able to find the ACCESS_DOMAIN_PERMISSION_ID.

Any thoughts?

Edit -

Disregard the above - it appears now I can impersonate a user in the domain to accomplish file creation as a non-developer.gserviceaccount.com user:

During the credential build process:

GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(jsonFactory)
    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)                
    .setServiceAccountScopes(scopes)                
    .setServiceAccountPrivateKeyFromP12File(pk12)
    .setServiceAccountUser(ACCESS_DOMAIN_IMPERSONATE)    
    .build();

The issue appears to be a delegation problem which may be solved with granting domain-wide authority to the service account.

domain-wide delegation

Will get back as to the success/failure of the above.


Solution

  • Delegating the domain-wide authority to the service account did the trick. I added the following scopes:

    https://www.googleapis.com/auth/drive
    https://docs.google.com/feeds
    https://spreadsheets.google.com/feeds
    

    Make sure you define these scopes in

    List<String> 
    

    when creating the GoogleCredential in your code.