Share files, folders and drives

To allow application users to share files and folders in Drive, use the Permissions API resource. You can retrieve permissions, verify users have permission to open a file, transfer file ownership, grant and revoke permissions, and use batch requests to change multiple permissions.

To share files and folders you specify permissions in an access control list (ACL), which is a list of permissions that determine whether or not users can perform actions on a file such as read or write.

For specific resource property definitions, see API Reference: Permissions .

Permission structure

Four fields define a file's permission: type, emailAddress, domain and role. These values work together to limit access appropriately, and are combined to define a complete permission.

The combination of these three fields identify one or more users:

  • type - limits access to one or more users (e.g user, group, domain or anyone)
  • emailAddress - provides a user or group to have access
  • domain - specifies domain to have access per the permission

The role field controls the user's ability to do something with the file (e.g. owner, organizer, writer).

Roles

Each permission in the Google Drive API has a role that defines what users can do with a file. This table shows the operations users can perform for each role.

Permitted operation organizer/owner fileOrganizer writer commenter reader
Read the metadata (e.g. name, description) of the file or folder
Read the content of the file
Read the list of items in the folder
Add comments to the file
Modify the metadata of the file or folder
Modify the content of the file
Access historical revisions
Add items to the folder
Remove items from the My Drive folder
Share a shared drive item
Add files to shared drives
Move items into the Trash
Reorganize items within a shared drive1
Move items outside of a shared drive2
Delete the file or folder
Delete items in shared drives2
Edit shared drive metadata
Add shared drive members
Delete an empty shared drive

Types and values

Every permission on a file or folder has a type, which is the scope of the permission, and determines which users have a role. Permissions with types user and groups also have an emailAddress. Permissions with type domain have a corresponding domain property that specifies the domain name. For example, a permission with a type of domain may have a domain of thecompany.com, indicating that the permission grants the given role to all users in the G Suite domain thecompany.com. This table defines all available types and values, and provides an example value.

Type Field Example
user emailAddress Email address of a user. (e.g. joe@thecompany.com)
group emailAddress Email address of a Google Group. (e.g. admins@thecompany.com)
domain domain Domain name of G Suite domain. (e.g. thecompany.com)
anyone N/A The anyone permission does not require an emailAddress or domain field.

IDs and names

The id is always the unique identifier of the permission value. IDs should be treated as opaque values.

The displayName is always the "pretty" name of the value of the permission. The following is a list of potential names for each type of permission.

Type Possible name values
user User's full name, as defined for their Google account. (e.g. Joe Smith)
group Name of the Google Group. (e.g. The Company Administrators)
domain String domain name. (e.g. thecompany.com)
anyone No displayName is present.

Permission propagation

ACLs that define folder permissions propagate downward to all contained items. Whenever permissions or the hierarchy are changed, the propagation occurs recursively through all nested folders.

Inherited permissions cannot be removed from an item in a shared drive. Instead they can be adjusted on the direct or indirect parent from which it was inherited. Inherited permissions may be removed from items under "My Drive" or "Shared with me."

Capabilities

Capabilities are a collection of boolean fields that indicate whether or not an action can be performed on a file. The effective permissions for the current user are represented as capabilities in the file metadata.

Retrieve permissions for a file

Use the permissions.list to retrieve permissions for a file or folder in Drive.

Verify capabilities for apps to open files

When your app opens files, it should check the capabilities, and render the UI appropriately for the requesting user.

Specify permissions for shared drive files

The role field of a permission reflects the effective role the user, group or domain has for a given item. To determine the source of the effective role, use the permissionDetails field. This field enumerates all inherited and direct file permissions for the user, group, or domain.

Grant or change permissions

Use permissions.create to grant additional permissions to a user, group, or domain. To change the assigned role, permissions.update.

Permissions may be granted on individual items in a shared drive even if the target user or group is already a member. If the new role is more permissive than the role granted via their membership, the new permission becomes the effective role for the selected items.

Revoke access

To revoke access to an item, delete the permission. This is also used to delete any direct file access permissions on a shared drive item.

For items in "My Drive", it is possible to delete an inherited permission. Doing so revokes access to the item and child items, if any.

For items in a shared drive, inherited permissions can not be revoked. Update or revoke the permission on the parent item instead.

Transfer file ownership

To transfer ownership of a file, create or update a permission with the owner role and set the transerOwnership query parameter to true. When a file is transferred, the previous owner's role is downgraded to writer.

Ownership transfers are not supported for items in shared drives. Ownership transfers are implicit when a user moves an item in or out of a shared drive.

Change multiple permissions with batch requests

We strongly recommend using batch requests to modify multiple permissions.

Examples

Here are examples of performing a batch permission modification with our Drive API client libraries.

Java

String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
JsonBatchCallback<Permission> callback = new JsonBatchCallback<Permission>() {
  @Override
  public void onFailure(GoogleJsonError e,
                        HttpHeaders responseHeaders)
      throws IOException {
    // Handle error
    System.err.println(e.getMessage());
  }

  @Override
  public void onSuccess(Permission permission,
                        HttpHeaders responseHeaders)
      throws IOException {
    System.out.println("Permission ID: " + permission.getId());
  }
};
BatchRequest batch = driveService.batch();
Permission userPermission = new Permission()
    .setType("user")
    .setRole("writer")
    .setEmailAddress("user@example.com");
driveService.permissions().create(fileId, userPermission)
    .setFields("id")
    .queue(batch, callback);

Permission domainPermission = new Permission()
    .setType("domain")
    .setRole("reader")
    .setDomain("example.com");
driveService.permissions().create(fileId, domainPermission)
    .setFields("id")
    .queue(batch, callback);

batch.execute();

Python

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ'
def callback(request_id, response, exception):
    if exception:
        # Handle error
        print exception
    else:
        print "Permission Id: %s" % response.get('id')

batch = drive_service.new_batch_http_request(callback=callback)
user_permission = {
    'type': 'user',
    'role': 'writer',
    'emailAddress': 'user@example.com'
}
batch.add(drive_service.permissions().create(
        fileId=file_id,
        body=user_permission,
        fields='id',
))
domain_permission = {
    'type': 'domain',
    'role': 'reader',
    'domain': 'example.com'
}
batch.add(drive_service.permissions().create(
        fileId=file_id,
        body=domain_permission,
        fields='id',
))
batch.execute()

PHP

$fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
$driveService->getClient()->setUseBatch(true);
try {
    $batch = $driveService->createBatch();

    $userPermission = new Google_Service_Drive_Permission(array(
        'type' => 'user',
        'role' => 'writer',
        'emailAddress' => 'user@example.com'
    ));
    $request = $driveService->permissions->create(
        $fileId, $userPermission, array('fields' => 'id'));
    $batch->add($request, 'user');
    $domainPermission = new Google_Service_Drive_Permission(array(
        'type' => 'domain',
        'role' => 'reader',
        'domain' => 'example.com'
    ));
    $request = $driveService->permissions->create(
        $fileId, $domainPermission, array('fields' => 'id'));
    $batch->add($request, 'domain');
    $results = $batch->execute();

    foreach ($results as $result) {
        if ($result instanceof Google_Service_Exception) {
            // Handle error
            printf($result);
        } else {
            printf("Permission ID: %s\n", $result->id);
        }
    }
} finally {
    $driveService->getClient()->setUseBatch(false);
}

.NET

var fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
var batch = new BatchRequest(driveService);
BatchRequest.OnResponse<Permission> callback = delegate (
    Permission permission,
    RequestError error,
    int index,
    System.Net.Http.HttpResponseMessage message)
{
    if (error != null)
    {
        // Handle error
        Console.WriteLine(error.Message);
    }
    else
    {
        Console.WriteLine("Permission ID: " + permission.Id);
    }
};
Permission userPermission = new Permission()
{
    Type = "user",
    Role = "writer",
    EmailAddress = "user@example.com"
};
var request = driveService.Permissions.Create(userPermission, fileId);
request.Fields = "id";
batch.Queue(request, callback);

Permission domainPermission = new Permission()
{
    Type = "domain",
    Role = "reader",
    Domain = "example.com"
};
request = driveService.Permissions.Create(domainPermission, fileId);
request.Fields = "id";
batch.Queue(request, callback);
var task = batch.ExecuteAsync();

Ruby

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ'
callback = lambda do |res, err|
  if err
    # Handle error...
    puts err.body
  else
    puts "Permission ID: #{res.id}"
  end
end
drive_service.batch do |service|
  user_permission = {
      type: 'user',
      role: 'writer',
      email_address: 'user@example.com'
  }
  service.create_permission(file_id,
                            user_permission,
                            fields: 'id',
                            &callback)
  domain_permission = {
      type: 'domain',
      role: 'reader',
      domain: 'example.com'
  }
  service.create_permission(file_id,
                            domain_permission,
                            fields: 'id',
                            &callback)
end

Node.js

var fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
var permissions = [
  {
    'type': 'user',
    'role': 'writer',
    'emailAddress': 'user@example.com'
  }, {
    'type': 'domain',
    'role': 'writer',
    'domain': 'example.com'
  }
];
// Using the NPM module 'async'
async.eachSeries(permissions, function (permission, permissionCallback) {
  drive.permissions.create({
    resource: permission,
    fileId: fileId,
    fields: 'id',
  }, function (err, res) {
    if (err) {
      // Handle error...
      console.error(err);
      permissionCallback(err);
    } else {
      console.log('Permission ID: ', res.id)
      permissionCallback();
    }
  });
}, function (err) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // All permissions inserted
  }
});

Objective-C

NSString *fileId = @"1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ";
GTLRBatchQuery *batchQuery = [GTLRBatchQuery batchQuery];

GTLRDrive_Permission *userPermission = [GTLRDrive_Permission object];
userPermission.type = @"user";
userPermission.role = @"writer";
userPermission.emailAddress = @"user@example.com";
GTLRDriveQuery_PermissionsCreate *createUserPermission =
    [GTLRDriveQuery_PermissionsCreate queryWithObject:userPermission
                                               fileId:fileId];
createUserPermission.fields = @"id";
createUserPermission.completionBlock = ^(GTLRServiceTicket *ticket,
                           GTLRDrive_Permission *permission,
                           NSError *error) {
    if (error == nil) {
        NSLog(@"Permisson ID: %@", permission.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }

};
[batchQuery addQuery:createUserPermission];

GTLRDrive_Permission *domainPermission = [GTLRDrive_Permission object];
domainPermission.type = @"domain";
domainPermission.role = @"reader";
domainPermission.domain = @"example.com";

GTLRDriveQuery_PermissionsCreate *createDomainPermission =
    [GTLRDriveQuery_PermissionsCreate queryWithObject:domainPermission
                                               fileId:fileId];
createDomainPermission.fields = @"id";
createDomainPermission.completionBlock = ^(GTLRServiceTicket *ticket,
                           GTLRDrive_Permission *permission,
                           NSError *error) {
    if (error == nil) {
        NSLog(@"Permisson ID: %@", permission.identifier);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
};
[batchQuery addQuery:createDomainPermission];

[driveService executeQuery:batchQuery completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRBatchResult *batchResult,
                                                     NSError *error) {
    if (error) {
        NSLog(@"An error occurred: %@", error);
    }
}];

다음에 대한 의견 보내기...

도움이 필요하시나요? 지원 페이지를 방문하세요.