Protect file content  |  Google Drive  |  Google for Developers (2024)

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

Make files read-only with Drive content restrictions

You can add a content restriction to a Google Drive file to prevent users fromdoing 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 aDrive item to be made read-only without changing the item'saccess permissions. This means it'snot an access restriction. While users cannot modify the file's content, otheroperations are still allowed based on access level (for example, a user withedit access can still move an item or change its sharing settings).

To add or remove a content restriction on a file in Drive, a usermust have the associatedpermissions. For a file or folder inMy Drive or a shared drive with thecapabilities.canModifyEditorContentRestriction, you must have role=writerassigned. For a file or folder in My Drive or a shared drive withan ownerRestricted content restriction, you must own the file or haverole=organizer. To view an item with a content restriction, users must haverole=reader or higher. For a complete list of roles, see . To change permissions on a file, seeChange permissions.

You can use the contentRestrictions.readOnly boolean field on thefiles resource to seta content restriction. Note that setting a content restriction on an itemoverwrites the existing one.

Scenarios for content restrictions

A content restriction on a Drive item signals to users that thecontents 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 notmeant to prevent users with sufficient permissions from continuing to work on anitem. Additionally, it isn't a way to create an immutable record.Drive content restrictions are mutable, so a content restrictionon 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 theslides

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

  • Google Forms
  • Google Sites
  • Google Drawings
  • Shortcuts and third-party shortcuts. For more information, see Create ashortcut file to content stored by yourapp and Create a shortcut to aDrive file.

Add a content restriction

To add a file content restriction, use thefiles.update method with thecontentRestrictions.readOnly field set to true. Add an optional reason forwhy you're adding the restriction, such as "Finalized contract." The followingcode 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 tomodify.

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

Protect file content | Google Drive | Google for Developers (1)

Remove a content restriction

To remove a file content restriction, use the files.update method with thecontentRestrictions.readOnly field set to false. The following code sampleshows 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 tomodify.

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 andallow content editing (provided you have the correct permissions). There are twooptions to do this:

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

    Protect file content | Google Drive | Google for Developers (2)
  2. Open the file with a content restriction and click (Locked mode)lock >Unlock file.

    Protect file content | Google Drive | Google for Developers (3)

Check for a content restriction

To check for a content restriction, use thefiles.get method with thecontentRestrictions returned field. The following code sample shows how tocheck 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 tocheck.

When you run the sample code, the method returns aContentRestrictionresource 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 withthe contentRestrictions.ownerRestricted boolean field set to true. Thefollowing code sample shows how to add a content restriction for file ownersonly:

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 tomodify.

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

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

Content restriction capabilities

A files resource contains acollection of boolean capabilities fields used to indicate whether an actioncan be performed on a file.

Content restrictions contain the following capabilities:

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

For more information, seeCapabilities.

For an example of retrieving file capabilities, see Verify userpermissions.

Prevent users from downloading, printing, or copying your file

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

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

Protect file content  |  Google Drive  |  Google for Developers (2024)

FAQs

Can I protect a file in Google Drive? ›

Click on Info. On the right side, click the Protect document menu. Select the Encrypt with Password option. Type a password to protect the document.

How do I lock content in Google Drive? ›

You can now lock files to prevent reviewers from making changes. Edits, comments, and suggestions can't be added to a locked document. To lock a file in Google Drive, right-click the file, select File information, and click Lock. A pop-up window will confirm that you want to lock the file.

How do I restrict access to a file in Google Drive? ›

When you change an item's general access to Restricted, only people with access can open the file.
  1. Find the file or folder in Google Drive, Google Docs, Google Sheets, or Google Slides.
  2. Open or select the file or folder.
  3. Click Share or Share. ...
  4. Under “General access”, click the Down arrow .
  5. Select Restricted.
  6. Click Done.

How do I protect a Google sheet in Google Drive? ›

Protect a sheet or range
  1. Open a spreadsheet in Google Sheets.
  2. Click Data. Protect sheets and ranges. ...
  3. Click Add a sheet or range or click an existing protection to edit it.
  4. To protect a range, click Range. To protect a sheet, click Sheet. ...
  5. Click Set permissions or Change permissions.
  6. Choose how you want to limit editing:

Can you make Google Drive files private? ›

Click Share button. Under General access, click the Down arrow . Choose who can access the file, in this case will be Private or Restricted. Click Done.

Can I Encrypt files on Google Drive? ›

Go to drive.google.com. At the top left, click New . click Encrypt and upload file.

What happens if I lock a file on Google Drive? ›

Tuesday, September 5, 2023

Locking a file makes sure reviewers can't change a file. Edits, comments and suggestions can't be added to locked documents.

How to protect a file from being deleted in Google Drive? ›

Prevent users from deleting files and folders
  1. In Google Drive, open an AODocs library where you are defined as an library administrator.
  2. Click the gear button and select Security center.
  3. In the Security center dialog, select the Security tab.
  4. Select the checkbox Only administrators can delete files and folders.
Mar 19, 2024

How do I put a password on a Google Drive file? ›

How to Password Protect Google Drive Folder on PC (4 Ways)
  1. Right-click the folder you want to encrypt and select Properties from the menu.
  2. Click the Advanced button under the General tab.
  3. In the Advanced Attributes window, go to Compress or Encrypt attributes, check the box of Encrypt contents to secure data.
  4. Click OK.

How do I lock a folder in Google Drive? ›

Protect your files with Safe folder
  1. On your Android device, open the Files by Google app .
  2. Scroll to "Collections."
  3. Tap Safe folder.
  4. Tap either PIN or Pattern. If PIN is selected: Enter your PIN. Tap Next. In the "Confirm PIN" screen, re-enter your PIN. Tap Next. In the "Remember your PIN" screen, tap Got it.

How to make a file not downloadable in Google Drive? ›

To prevent your files in Google Drive from being downloaded, printed and copied: Select one or more files in Google Drive, click Share. In the top right corner click on the gear icon. Uncheck the box “Viewers and commenters can see the option to download, print, and copy.”

Does Google Drive have an API? ›

The Google Drive API lets you create apps that leverage Google Drive cloud storage. You can develop applications that integrate with Drive, and create robust functionality in your application using the Drive API.

Does Google Drive protect your files? ›

Are files and links in Google Drive secure? Files stored in Google Drive are encrypted in-transit and at-rest. That means even if an unauthorized user accesses the files, they remain protected.

How do I protect my Google Drive account? ›

8 tips for making Google Drive more secure
  1. Use two-factor authentication (2FA) ...
  2. Setup recovery on your account. ...
  3. Use data encryption. ...
  4. Consider data classification. ...
  5. Set up endpoint management. ...
  6. Automate backup processes. ...
  7. Control user permissions in the application. ...
  8. Third-party apps.

How do I protect my Google Docs? ›

How to password protect a Google Doc
  1. Open the document in Google Drive.
  2. Click on “File” and then highlight “Download”. Select “PDF” from the dropdown menu.
  3. Locate the PDF in your operating system's file explorer.
  4. Right-click on the file and a dialog box will appear. ...
  5. From there, select the option to add a password.

Can I put a password on a folder in Google Drive? ›

Google Drive does not offer this type of security. On top of that, we offer a lot more access control options when you share folders. For example, besides letting you decide exactly who to share your files with and allowing you to revoke access at any time, you can also set expiration dates on links.

How to make a Google Drive file read only? ›

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.

Can you password protect a file? ›

Go to File > Info > Protect Document > Encrypt with Password.

Is it safe to keep sensitive documents in Google Drive? ›

You probably store dozens of miscellaneous documents and files on Google Drive without a second thought. But is it safe to put sensitive files in Google Drive? Generally, it's secure because Google encrypts your data while it's stored or transferred.

Top Articles
4% rule and the game
Spotify keeps pausing? Here’s how to fix it
Spectrum Gdvr-2007
Toa Guide Osrs
South Carolina defeats Caitlin Clark and Iowa to win national championship and complete perfect season
Richard Sambade Obituary
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
The Pope's Exorcist Showtimes Near Cinemark Hollywood Movies 20
Cars For Sale Tampa Fl Craigslist
83600 Block Of 11Th Street East Palmdale Ca
The Connecticut Daily Lottery Hub
California Department of Public Health
Guidewheel lands $9M Series A-1 for SaaS that boosts manufacturing and trims carbon emissions | TechCrunch
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Walmart stores in 6 states no longer provide single-use bags at checkout: Which states are next?
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Strange World Showtimes Near Roxy Stadium 14
20 Different Cat Sounds and What They Mean
Amazing Lash Studio Casa Linda
Rochester Ny Missed Connections
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
27 Paul Rudd Memes to Get You Through the Week
11 Ways to Sell a Car on Craigslist - wikiHow
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
The Banshees Of Inisherin Showtimes Near Broadway Metro
4Oxfun
Keyn Car Shows
Marlene2995 Pagina Azul
Delete Verizon Cloud
How To Improve Your Pilates C-Curve
Lesson 1.1 Practice B Geometry Answers
Little Einsteins Transcript
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Egg Crutch Glove Envelope
Lowell Car Accident Lawyer Kiley Law Group
The Ride | Rotten Tomatoes
Prima Healthcare Columbiana Ohio
Zero Sievert Coop
Deshuesadero El Pulpo
Uvalde Topic
Arigreyfr
Fairbanks Auto Repair - University Chevron
Ucla Basketball Bruinzone
About us | DELTA Fiber
Google Flights Missoula
Tìm x , y , z :a, \(\frac{x+z+1}{x}=\frac{z+x+2}{y}=\frac{x+y-3}{z}=\)\(\frac{1}{x+y+z}\)b, 10x = 6y và \(2x^2\)\(-\) \(...
Assignation en paiement ou injonction de payer ?
Convert Celsius to Kelvin
Kobe Express Bayside Lakes Photos
Southern Blotting: Principle, Steps, Applications | Microbe Online
Cataz.net Android Movies Apk
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated:

Views: 5779

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.