使用者必須授權指令碼專案存取自己的資料或代表自己執行動作。使用者首次執行需要授權的指令碼時,使用者介面會顯示提示,要求啟動授權流程。
在這個流程中,UI 會告知使用者指令碼要求的權限。舉例來說,指令碼可能會要求讀取電子郵件或建立日曆活動的權限。指令碼專案會將這些個別權限定義為 OAuth 範圍。
對於大多數指令碼,Apps Script 會自動偵測必要範圍。您隨時可以查看指令碼使用的範圍。您也可以使用網址字串,在資訊清單中明確設定範圍。發布的應用程式 (例如外掛程式) 必須盡可能使用最窄的範圍。
在授權流程中,Apps Script 會以人類可解讀的說明呈現必要範圍。舉例來說,如果指令碼需要試算表的唯讀存取權,資訊清單可能包含 https://www.googleapis.com/auth/spreadsheets.readonly 範圍。授權提示會要求使用者「查看您的 Google 試算表」。
部分範圍包含其他範圍。舉例來說,授權存取 https://www.googleapis.com/auth/spreadsheets 可讀取及寫入試算表。
在某些介面 (例如 Apps Script IDE),使用者會看到精細 OAuth 同意畫面。使用者可以在這個畫面中選取要授予的特定權限,而不必一次授予所有權限。設計指令碼,處理精細 OAuth 權限。
查看範圍
如要查看指令碼專案所需的範圍,請按照下列步驟操作:
- 開啟指令碼專案。
- 按一下左側的「總覽」 。
- 查看「專案 OAuth 範圍」下的範圍。
設定明確範圍
Apps Script 會掃描程式碼中的函式呼叫,自動判斷所需範圍。雖然這對大多數指令碼來說已足夠,但您必須對已發布的外掛程式、網路應用程式、Chat 應用程式和 Chat API 呼叫進行更直接的控制。
Apps Script 有時會自動指派寬鬆的範圍。這可能表示指令碼要求使用者提供超出需求的存取權。如果是已發布的指令碼,請將廣泛範圍替換為涵蓋指令碼需求的有限範圍。
您可以編輯指令碼專案的資訊清單檔案,明確設定專案使用的範圍。oauthScopes 資訊清單欄位是專案使用的範圍陣列。如要設定專案的範圍,請按照下列步驟操作:
- 開啟指令碼專案。
- 按一下左側的「專案設定」 。
- 勾選「在編輯器中顯示『appsscript.json』資訊清單檔案」核取方塊。
- 按一下左側的「編輯器」圖示 。
- 按一下左側的
appsscript.json檔案。 - 找到標示為
oauthScopes的頂層欄位。如果沒有,可以自行新增。 - 將
oauthScopes陣列的內容替換為專案要使用的範圍。例如:{ ... "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets.readonly", "https://www.googleapis.com/auth/userinfo.email" ], ... } - 按一下頂端的「儲存」圖示 。
處理精細 OAuth 權限
精細 OAuth 同意畫面最初是為直接執行指令碼的使用者,在 Apps Script IDE 中推出。同意畫面會隨著時間,逐步發布至其他平台,例如巨集、觸發條件和外掛程式。詳情請參閱「在 Google Apps Script IDE 執行作業時,取得精細的 OAuth 同意聲明」。
使用者進入精細 OAuth 同意畫面後,可以指定要授權的個別 OAuth 範圍。使用者可精細控管要與每個指令碼共用的帳戶資料。舉例來說,如果指令碼要求電子郵件和日曆範圍,使用者可以選擇授予日曆權限,但拒絕授予 Gmail 權限。
下列各節說明如何處理精細 OAuth 權限。
自動要求必要範圍的權限
如果執行流程需要特定範圍,您可以要求使用者授予這些權限。指令碼可以檢查權限,並在缺少權限時自動要求。
ScriptApp 類別的下列方法會驗證權限,並顯示授權提示:
requireScopes(authMode, oAuthScopes):如果流程需要特定範圍,請使用這個方法。requireAllScopes(authMode):如果執行流程需要所有專案範圍,請使用這個方法。
範例
以下範例說明如何呼叫 requireScopes() 和 requireAllScopes()。這個指令碼會使用 Gmail、Google 試算表和日曆的範圍。sendEmail() 函式只需要 Gmail 和 Google 試算表的範圍,而 createEventSendEmail() 函式則需要指令碼使用的所有範圍。
// This function requires the Gmail and Sheets scopes.
function sendEmail() {
// Validates that the user has granted permission for the Gmail and Sheets scopes.
// If not, the execution ends and prompts the user for authorization.
ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [
'https://mail.google.com/',
'https://www.googleapis.com/auth/spreadsheets'
]);
// Sends an email.
GmailApp.sendEmail("dana@example.com", "Subject", "Body");
Logger.log("Email sent successfully!");
// Opens a spreadsheet and sheet to track the sent email.
const ss = SpreadsheetApp.openById("abc1234567");
const sheet = ss.getSheetByName("Email Tracker")
// Gets the last row of the sheet.
const lastRow = sheet.getLastRow();
// Adds "Sent" to column E of the last row of the spreadsheet.
sheet.getRange(lastRow, 5).setValue("Sent");
Logger.log("Sheet updated successfully!");
}
// This function requires all scopes used by the script (Gmail,
// Calendar, and Sheets).
function createEventSendEmail() {
// Validates that the user has granted permission for all scopes used by the
// script. If not, the execution ends and prompts the user for authorization.
ScriptApp.requireAllScopes(ScriptApp.AuthMode.FULL);
// Creates an event.
CalendarApp.getDefaultCalendar().createEvent(
"Meeting",
new Date("November 28, 2024 10:00:00"),
new Date("November 28, 2024 11:00:00")
);
Logger.log("Calendar event created successfully!");
// Sends an email.
GmailApp.sendEmail("dana@example.com", "Subject 2", "Body 2");
Logger.log("Email sent successfully!");
// Opens a spreadsheet and sheet to track the created meeting and sent email.
const ss = SpreadsheetApp.openById("abc1234567");
const sheet = ss.getSheetByName("Email and Meeting Tracker")
// Gets the last row
const lastRow = sheet.getLastRow();
// Adds "Sent" to column E of the last row
sheet.getRange(lastRow, 5).setValue("Sent");
// Adds "Meeting created" to column F of the last row
sheet.getRange(lastRow, 6).setValue("Meeting created");
Logger.log("Sheet updated successfully!");
}
為缺少範圍建立自訂體驗
您可以擷取使用者的權限狀態,並設計自訂體驗。 舉例來說,您可以停用需要缺少權限的功能,或是顯示說明需求的對話方塊。下列方法會擷取包含使用者權限資訊的物件,包括使用者已授權的範圍,以及要求任何缺少的範圍的網址:
getAuthorizationInfo(authMode, oAuthScopes):檢查特定範圍的權限狀態。getAuthorizationInfo(authMode): 檢查所有專案範圍的權限狀態。
如要從授權資訊物件取得權限詳細資料,例如授權範圍清單和要求缺少權限的網址,請使用 AuthorizationInfo 類別的方法。
範例
以下範例說明如何使用 getAuthorizationInfo(),略過使用者未授予必要範圍的相關功能。這樣一來,執行流程的其餘部分就能繼續進行,不必提示授權缺少的範圍。
// This function uses the Gmail scope and skips the email
// capabilities if the scope for Gmail hasn't been granted.
function myFunction() {
const authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL, ['https://mail.google.com/']);
if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.NOT_REQUIRED) {
GmailApp.sendEmail("dana@example.com", "Subject", "Body");
Logger.log("Email sent successfully!");
} else {
const scopesGranted = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL).getAuthorizedScopes();
console.warn(`Authorized scopes: ${scopesGranted} not enough to send mail, skipping.`);
}
// Continue the rest of the execution flow...
}
確認觸發程序執行作業具備權限
與觸發條件相關聯的函式會自動執行,使用者可能不在場,無法提供權限。建議您先使用
requireScopes(authMode, oAuthScopes)
,再安裝觸發條件。系統會提示使用者提供缺少的權限,且不允許在沒有權限的情況下安裝觸發程序。
範例
// This function requires scope Sheets.
function trackFormSubmissions(e){
// Opens a spreadsheet to track the sent email.
const ss = SpreadsheetApp.openById("abc1234567");
const sheet = ss.getSheetByName("Submission Tracker")
// Gets the last row of the sheet.
const lastRow = sheet.getLastRow();
// Adds email address of user that submitted the form
// to column E of the last row of the spreadsheet.
sheet.getRange(lastRow, 5).setValue(e.name);
Logger.log("Sheet updated successfully!");
}
function installTrigger(){
// Validates that the user has granted permissions for trigger
// installation and execution. If not, trigger doesn't get
// installed and prompts the user for authorization.
ScriptApp.requireScopes(ScriptApp.AuthMode.FULL, [
'https://www.googleapis.com/auth/script.scriptapp',
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/forms.currentonly'
]);
ScriptApp.newTrigger('trackFormSubmission')
.forForm(FormApp.getActiveForm())
.onFormSubmit()
.create();
}
OAuth 驗證
部分 OAuth 範圍屬於機密範圍,因為這些範圍允許存取 Google 使用者資料。如果指令碼專案使用的範圍允許存取使用者資料,專案必須先通過 OAuth 用戶端驗證,才能公開發布為網路應用程式或外掛程式。詳情請參閱下列指南:
受限制的範圍
除了敏感範圍,特定範圍也會歸類為受限制,並須遵守額外規則,以保護使用者資料。如果發布的應用程式使用受限範圍,則必須遵守所有規格。
發布前,請先參閱受限制範圍的完整清單。符合規定的應用程式必須遵守特定 API 範圍的附加規定。
請盡可能避免使用受限範圍,以簡化審查程序。您可以針對非公開應用程式,自由使用受限制的範圍。