ScriptApp.getIdentityToken() 메서드를 사용하여 유효 사용자의 OpenID Connect ID 토큰 (JSON 웹 토큰 또는 JWT)을 가져올 수 있습니다. 이 토큰을 사용하여 Cloud Run과 같이 토큰을 수락하도록 구성된 Google Cloud 서비스로 인증할 수 있습니다.
openid 범위 사용 설정
OpenID Connect ID 토큰을 생성하려면 openid 범위가 필요합니다. UrlFetch 서비스의 https://www.googleapis.com/auth/script.external_request와 같이 스크립트에서 사용하는 다른 범위도 나열해야 합니다. 이 예시에는 ID 토큰에 사용자의 이메일 주소를 추가하기 위해 https://www.googleapis.com/auth/userinfo.email 범위가 포함되어 있습니다.
스크립트 프로젝트의 매니페스트 파일 (appsscript.json)에서 openid 범위와 기타 필수 범위를 oauthScopes 배열에 추가합니다.
{
"timeZone": "America/New_York",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"openid",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/userinfo.email"
]
}
Google Cloud 서비스 구성
스크립트에 발급된 ID 토큰을 수락하도록 Google Cloud 서비스를 구성해야 합니다. 일반적으로 스크립트의 클라이언트 ID를 허용된 잠재고객으로 추가해야 합니다.
스크립트의 클라이언트 ID를 찾으려면 ID 토큰을 디코딩하면 됩니다.
function logClientId() {
const idToken = ScriptApp.getIdentityToken();
const body = idToken.split('.')[1];
const decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
const payload = JSON.parse(decoded);
Logger.log('Client ID: ' + payload.aud);
}
Cloud Run의 경우 이 클라이언트 ID를 허용하도록 맞춤 잠재고객을 구성할 수 있습니다.
인증된 요청 만들기
구성 후 요청의 Authorization 헤더에 ID 토큰을 포함할 수 있습니다.
function callCloudRunService() {
const idToken = ScriptApp.getIdentityToken();
const url = 'https://your-service-url.a.run.app';
const response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + idToken
}
});
Logger.log(response.getContentText());
}