Protect file content

The Google Drive API supports several ways to prevent file modification, including file content restriction and prohibiting the option to download, print, or copy files.

Make files read-only with Drive content restrictions

You can add a content restriction to a Google Drive file to prevent users from doing the following:

  • Modifying the title
  • Making content edits
  • Uploading a revision
  • Adding or modifying comments

Applying content restrictions is a mechanism that allows the content of a Drive item to be made read-only without changing the item's access permissions. This means it's not an access restriction. While users cannot modify the file's content, other operations are still allowed based on access level (for example, a user with edit access can still move an item or change its sharing settings).

To add or remove a content restriction on a file in Drive, a user must have the associated permissions. For a file or folder in My Drive or a shared drive with the capabilities.canModifyEditorContentRestriction, you must have role=writer assigned. For a file or folder in My Drive or a shared drive with an ownerRestricted content restriction, you must own the file or have role=organizer. To view an item with a content restriction, users must have role=reader or higher. For a complete list of roles, see Roles & permissions. To change permissions on a file, see Change permissions.

You can use the contentRestrictions.readOnly boolean field on the files resource to set a content restriction. Note that setting a content restriction on an item overwrites the existing one.

Scenarios for content restrictions

A content restriction on a Drive item signals to users that the contents shouldn't be changed. This can be for some of the following reasons:

  • Pausing work on a collaborative document during review or audit periods.
  • Setting an item to a finalized state, such as approved.
  • Preventing changes during a sensitive meeting.
  • Prohibiting external changes for workflows handled by automated systems.
  • Restricting edits by Google Apps Script and Google Workspace Add-ons.
  • Avoiding accidental edits to a document.

Note though that while content restrictions can help manage content, it's not meant to prevent users with sufficient permissions from continuing to work on an item. Additionally, it isn't a way to create an immutable record. Drive content restrictions are mutable, so a content restriction on an item doesn't guarantee that the item never changes.

Manage files with content restrictions

Google Docs, Google Sheets, and Google Slides, as well as all other files, can contain content restrictions.

A content restriction on an item prevents changes to its title and content, including:

  • Comments and suggestions (on Docs, Sheets, Slides, and binary files)
  • Revisions of a binary file
  • Text and formatting in Docs
  • Text or formulas in Sheets, a Sheets layout, and instances in Sheets
  • All content in Slides, as well as the order and number of the slides

Certain file types can't contain a content restriction. A few examples are:

Add a content restriction

To add a file content restriction, use the files.update method with the contentRestrictions.readOnly field set to true. Add an optional reason for why you're adding the restriction, such as "Finalized contract." The following code sample shows how to add a content restriction:

Java

File updatedFile =
  new File()
      .setContentRestrictions(
          ImmutableList.of(new ContentRestriction().setReadOnly(true).setReason("Finalized contract."));

File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();

Python

content_restriction = {'readOnly': True, 'reason':'Finalized contract.'}

response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();

Node.js

/**
* Set a content restriction on a file.
* @return{obj} updated file
**/
async function addContentRestriction() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});
  const contentRestriction = {
    'readOnly': True,
    'reason': 'Finalized contract.',
  };
  const updatedFile = {
    'contentRestrictions': [contentRestriction],
  };
  try {
    const response = await service.files.update({
      fileId: 'FILE_ID',
      resource: updatedFile,
      fields: 'contentRestrictions',
    });
    return response;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }
}

Replace FILE_ID with the fileId of the file that you want to modify.

When you run the sample code, the file is content restricted and a lock symbol () appears beside the file name within the Google Drive user interface (UI). The file is now read-only.

A file with a content restriction within a Drive file list.
Figure 1. A file with a content restriction within a Drive file list.

Remove a content restriction

To remove a file content restriction, use the files.update method with the contentRestrictions.readOnly field set to false. The following code sample shows how to remove a content restriction:

Java

File updatedFile =
new File()
    .setContentRestrictions(
        ImmutableList.of(new ContentRestriction().setReadOnly(false));

File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();

Python

content_restriction = {'readOnly': False}

response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();

Node.js

/**
* Remove a content restriction on a file.
* @return{obj} updated file
**/
async function removeContentRestriction() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});
  const contentRestriction = {
    'readOnly': False,
  };
  const updatedFile = {
    'contentRestrictions': [contentRestriction],
  };
  try {
    const response = await service.files.update({
      fileId: 'FILE_ID',
      resource: updatedFile,
      fields: 'contentRestrictions',
    });
    return response;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }
}

Replace FILE_ID with the fileId of the file that you want to modify.

When you run the sample code, the file is no longer content restricted.

You can also use the Drive UI to remove a content restriction and allow content editing (provided you have the correct permissions). There are two options to do this:

  1. In Drive, right-click the file with a content restriction and click Unlock .

    Remove a file content restriction within a Drive file list.
    Figure 2. Remove a file content restriction within a Drive file list.
  2. Open the file with a content restriction and click (Locked mode) > Unlock file.

    Remove a file content restriction within a document.
    Figure 3. Remove a file content restriction within a document.

Check for a content restriction

To check for a content restriction, use the files.get method with the contentRestrictions returned field. The following code sample shows how to check the status of a content restriction:

Java

File response = driveService.files().get("FILE_ID").setFields("contentRestrictions").execute();

Python

response = drive_service.files().get(fileId="FILE_ID", fields = "contentRestrictions").execute();

Node.js

/**
* Get content restrictions on a file.
* @return{obj} updated file
**/
async function fetchContentRestrictions() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});
  try {
    const response = await service.files.get({
      fileId: 'FILE_ID',
      fields: 'contentRestrictions',
    });
    return response;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }
}

Replace FILE_ID with the fileId of the file that you want to check.

When you run the sample code, the method returns a ContentRestriction resource if present.

Add a content restriction only the file owner can modify

To add a file content restriction so only file owners can toggle the mechanism, use the files.update method with the contentRestrictions.ownerRestricted boolean field set to true. The following code sample shows how to add a content restriction for file owners only:

Java

File updatedFile =
  new File()
      .setContentRestrictions(
          ImmutableList.of(new ContentRestriction().setReadOnly(true).setOwnerRestricted(true).setReason("Finalized contract."));

File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();

Python

content_restriction = {'readOnly': True, 'ownerRestricted': True, 'reason':'Finalized contract.'}

response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();

Node.js

/**
* Set an owner restricted content restriction on a file.
* @return{obj} updated file
**/
async function addOwnerRestrictedContentRestriction() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});
  const contentRestriction = {
    'readOnly': True,
    'ownerRestricted': True,
    'reason': 'Finalized contract.',
  };
  const updatedFile = {
    'contentRestrictions': [contentRestriction],
  };
  try {
    const response = await service.files.update({
      fileId: 'FILE_ID',
      resource: updatedFile,
      fields: 'contentRestrictions',
    });
    return response;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }
}

Replace FILE_ID with the fileId of the file that you want to modify.

When you run the sample code, the file is content restricted and only file owners can remove it. If you're the file owner, an active lock symbol () appears beside the file name within the Drive user interface (UI). If you're not the owner, the lock symbol is dimmed.

To remove the ownerRestricted flag, use the files.update method with the contentRestrictions.ownerRestricted field set to false.

Content restriction capabilities

A files resource contains a collection of boolean capabilities fields used to indicate whether an action can be performed on a file.

Content restrictions contain the following capabilities:

  • capabilities.canModifyEditorContentRestriction: Whether the current user can add or modify a content restriction.
  • capabilities.canModifyOwnerContentRestriction: Whether the current user can add or modify an owner content restriction.
  • capabilities.canRemoveContentRestriction: Whether the current user can remove the applied content restriction (if present).

For more information, see Capabilities.

For an example of retrieving file capabilities, see Verify user permissions.

Prevent users from downloading, printing, or copying your file

You can limit how users with role=commenter or role=reader permissions can download, print, and copy files within Drive, Docs, Sheets, and Slides.

To remove the options to download, print, and copy files, use the files.update method with the copyRequiresWriterPermission boolean field set to true.