OAuth2.0 库
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
为 OAuth2 授权的请求创建对象
/**
* Simple library for sending OAuth2 authenticated requests.
* See: https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#oauth_2
* for full details.
*/
/**
* Adds a OAuth object, for creating authenticated requests, to the global
* object.
*/
(function(scope) {
/**
* Creates an object for making authenticated URL fetch requests with a
* given stored access token.
* @param {string} accessToken The access token to store and use.
* @constructor
*/
function OAuth2UrlFetchApp(accessToken) { this.accessToken_ = accessToken; }
/**
* Performs an HTTP request for the given URL.
* @param {string} url The URL to fetch
* @param {?Object=} options Options as per UrlFetchApp.fetch
* @return {!HTTPResponse} The HTTP Response object.
*/
OAuth2UrlFetchApp.prototype.fetch = function(url, opt_options) {
const fetchOptions = opt_options || {};
if (!fetchOptions.headers) {
fetchOptions.headers = {};
}
fetchOptions.headers.Authorization = 'Bearer ' + this.accessToken_;
return UrlFetchApp.fetch(url, fetchOptions);
};
/**
* Performs the authentication step
* @param {string} tokenUrl The endpoint for use in obtaining the token.
* @param {!Object} payload The authentication payload, typically containing
* details of the grant type, credentials etc.
* @param {string=} opt_authHeader Client credential grant also can make use
* of an Authorisation header, as specified here
* @param {string=} opt_scope Optional string of spaced-delimited scopes.
* @return {string} The access token
*/
function authenticate_(tokenUrl, payload, opt_authHeader, opt_scope) {
const options = {muteHttpExceptions: true, method: 'POST', payload: payload};
if (opt_scope) {
options.payload.scope = opt_scope;
}
if (opt_authHeader) {
options.headers = {Authorization: opt_authHeader};
}
const response = UrlFetchApp.fetch(tokenUrl, options);
const responseData = JSON.parse(response.getContentText());
if (responseData && responseData.access_token) {
const accessToken = responseData.access_token;
} else {
throw Error('No access token received: ' + response.getContentText());
}
return accessToken;
}
/**
* Creates a OAuth2UrlFetchApp object having authenticated with a refresh
* token.
* @param {string} tokenUrl The endpoint for use in obtaining the token.
* @param {string} clientId The client ID representing the application.
* @param {string} clientSecret The client secret.
* @param {string} refreshToken The refresh token obtained through previous
* (possibly interactive) authentication.
* @param {string=} opt_scope Space-delimited set of scopes.
* @return {!OAuth2UrlFetchApp} The object for making authenticated requests.
*/
function withRefreshToken(
tokenUrl, clientId, clientSecret, refreshToken, opt_scope) {
const payload = {
grant_type: 'refresh_token',
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken
};
const accessToken = authenticate_(tokenUrl, payload, null, opt_scope);
return new OAuth2UrlFetchApp(accessToken);
}
/**
* Creates a OAuth2UrlFetchApp object having authenticated with client
* credentials.
* @param {string} tokenUrl The endpoint for use in obtaining the token.
* @param {string} clientId The client ID representing the application.
* @param {string} clientSecret The client secret.
* @param {string=} opt_scope Space-delimited set of scopes.
* @return {!OAuth2UrlFetchApp} The object for making authenticated requests.
*/
function withClientCredentials(tokenUrl, clientId, clientSecret, opt_scope) {
const authHeader =
'Basic ' + Utilities.base64Encode([clientId, clientSecret].join(':'));
const payload = {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret
};
const accessToken = authenticate_(tokenUrl, payload, authHeader, opt_scope);
return new OAuth2UrlFetchApp(accessToken);
}
/**
* Creates a OAuth2UrlFetchApp object having authenticated with OAuth2 username
* and password.
* @param {string} tokenUrl The endpoint for use in obtaining the token.
* @param {string} clientId The client ID representing the application.
* @param {string} username OAuth2 Username
* @param {string} password OAuth2 password
* @param {string=} opt_scope Space-delimited set of scopes.
* @return {!OAuth2UrlFetchApp} The object for making authenticated requests.
*/
function withPassword(tokenUrl, clientId, username, password, opt_scope) {
const payload = {
grant_type: 'password',
client_id: clientId,
username: username,
password: password
};
const accessToken = authenticate_(tokenUrl, payload, null, opt_scope);
return new OAuth2UrlFetchApp(accessToken);
}
/**
* Creates a OAuth2UrlFetchApp object having authenticated as a Service
* Account.
* Flow details taken from:
* https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* @param {string} tokenUrl The endpoint for use in obtaining the token.
* @param {string} serviceAccount The email address of the Service Account.
* @param {string} key The key taken from the downloaded JSON file.
* @param {string} scope Space-delimited set of scopes.
* @return {!OAuth2UrlFetchApp} The object for making authenticated requests.
*/
function withServiceAccount(tokenUrl, serviceAccount, key, scope) {
const assertionTime = new Date();
const jwtHeader = '{"alg":"RS256","typ":"JWT"}';
const jwtClaimSet = {
iss: serviceAccount,
scope: scope,
aud: tokenUrl,
exp: Math.round(assertionTime.getTime() / 1000 + 3600),
iat: Math.round(assertionTime.getTime() / 1000)
};
const jwtAssertion = Utilities.base64EncodeWebSafe(jwtHeader) + '.' +
Utilities.base64EncodeWebSafe(JSON.stringify(jwtClaimSet));
const signature = Utilities.computeRsaSha256Signature(jwtAssertion, key);
jwtAssertion += '.' + Utilities.base64Encode(signature);
const payload = {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwtAssertion
};
const accessToken = authenticate_(tokenUrl, payload, null);
return new OAuth2UrlFetchApp(accessToken);
}
scope.OAuth2 = {
withRefreshToken: withRefreshToken,
withClientCredentials: withClientCredentials,
withServiceAccount: withServiceAccount,
withPassword: withPassword
};
})(this);
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[[["\u003cp\u003eProvides a simplified library for sending OAuth2-authenticated HTTP requests within Google Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eOffers different authentication methods including refresh token, client credentials, service account and password.\u003c/p\u003e\n"],["\u003cp\u003eUses \u003ccode\u003eUrlFetchApp\u003c/code\u003e to perform the actual HTTP requests after obtaining an access token.\u003c/p\u003e\n"],["\u003cp\u003eAbstracts away the complexity of OAuth2 authentication flows for various use cases.\u003c/p\u003e\n"],["\u003cp\u003eReturns an \u003ccode\u003eOAuth2UrlFetchApp\u003c/code\u003e object enabling authorized requests with the access token.\u003c/p\u003e\n"]]],[],null,["# OAuth2.0 library\n\nCreate an object for OAuth2-authorized requests\n-----------------------------------------------\n\n```gdscript\n/**\n * Simple library for sending OAuth2 authenticated requests.\n * See: https://developers.google.com/google-ads/scripts/docs/features/third-party-apis#oauth_2\n * for full details.\n */\n\n/**\n * Adds a OAuth object, for creating authenticated requests, to the global\n * object.\n */\n(function(scope) {\n /**\n * Creates an object for making authenticated URL fetch requests with a\n * given stored access token.\n * @param {string} accessToken The access token to store and use.\n * @constructor\n */\n function OAuth2UrlFetchApp(accessToken) { this.accessToken_ = accessToken; }\n\n /**\n * Performs an HTTP request for the given URL.\n * @param {string} url The URL to fetch\n * @param {?Object=} options Options as per UrlFetchApp.fetch\n * @return {!HTTPResponse} The HTTP Response object.\n */\n OAuth2UrlFetchApp.prototype.fetch = function(url, opt_options) {\n const fetchOptions = opt_options || {};\n if (!fetchOptions.headers) {\n fetchOptions.headers = {};\n }\n fetchOptions.headers.Authorization = 'Bearer ' + this.accessToken_;\n return UrlFetchApp.fetch(url, fetchOptions);\n };\n\n /**\n * Performs the authentication step\n * @param {string} tokenUrl The endpoint for use in obtaining the token.\n * @param {!Object} payload The authentication payload, typically containing\n * details of the grant type, credentials etc.\n * @param {string=} opt_authHeader Client credential grant also can make use\n * of an Authorisation header, as specified here\n * @param {string=} opt_scope Optional string of spaced-delimited scopes.\n * @return {string} The access token\n */\n function authenticate_(tokenUrl, payload, opt_authHeader, opt_scope) {\n const options = {muteHttpExceptions: true, method: 'POST', payload: payload};\n if (opt_scope) {\n options.payload.scope = opt_scope;\n }\n if (opt_authHeader) {\n options.headers = {Authorization: opt_authHeader};\n }\n const response = UrlFetchApp.fetch(tokenUrl, options);\n const responseData = JSON.parse(response.getContentText());\n if (responseData && responseData.access_token) {\n const accessToken = responseData.access_token;\n } else {\n throw Error('No access token received: ' + response.getContentText());\n }\n return accessToken;\n }\n\n /**\n * Creates a OAuth2UrlFetchApp object having authenticated with a refresh\n * token.\n * @param {string} tokenUrl The endpoint for use in obtaining the token.\n * @param {string} clientId The client ID representing the application.\n * @param {string} clientSecret The client secret.\n * @param {string} refreshToken The refresh token obtained through previous\n * (possibly interactive) authentication.\n * @param {string=} opt_scope Space-delimited set of scopes.\n * @return {!OAuth2UrlFetchApp} The object for making authenticated requests.\n */\n function withRefreshToken(\n tokenUrl, clientId, clientSecret, refreshToken, opt_scope) {\n const payload = {\n grant_type: 'refresh_token',\n client_id: clientId,\n client_secret: clientSecret,\n refresh_token: refreshToken\n };\n const accessToken = authenticate_(tokenUrl, payload, null, opt_scope);\n return new OAuth2UrlFetchApp(accessToken);\n }\n\n /**\n * Creates a OAuth2UrlFetchApp object having authenticated with client\n * credentials.\n * @param {string} tokenUrl The endpoint for use in obtaining the token.\n * @param {string} clientId The client ID representing the application.\n * @param {string} clientSecret The client secret.\n * @param {string=} opt_scope Space-delimited set of scopes.\n * @return {!OAuth2UrlFetchApp} The object for making authenticated requests.\n */\n function withClientCredentials(tokenUrl, clientId, clientSecret, opt_scope) {\n const authHeader =\n 'Basic ' + Utilities.base64Encode([clientId, clientSecret].join(':'));\n const payload = {\n grant_type: 'client_credentials',\n client_id: clientId,\n client_secret: clientSecret\n };\n const accessToken = authenticate_(tokenUrl, payload, authHeader, opt_scope);\n return new OAuth2UrlFetchApp(accessToken);\n }\n\n /**\n * Creates a OAuth2UrlFetchApp object having authenticated with OAuth2 username\n * and password.\n * @param {string} tokenUrl The endpoint for use in obtaining the token.\n * @param {string} clientId The client ID representing the application.\n * @param {string} username OAuth2 Username\n * @param {string} password OAuth2 password\n * @param {string=} opt_scope Space-delimited set of scopes.\n * @return {!OAuth2UrlFetchApp} The object for making authenticated requests.\n */\n function withPassword(tokenUrl, clientId, username, password, opt_scope) {\n const payload = {\n grant_type: 'password',\n client_id: clientId,\n username: username,\n password: password\n };\n const accessToken = authenticate_(tokenUrl, payload, null, opt_scope);\n return new OAuth2UrlFetchApp(accessToken);\n }\n\n /**\n * Creates a OAuth2UrlFetchApp object having authenticated as a Service\n * Account.\n * Flow details taken from:\n * https://developers.google.com/identity/protocols/OAuth2ServiceAccount\n * @param {string} tokenUrl The endpoint for use in obtaining the token.\n * @param {string} serviceAccount The email address of the Service Account.\n * @param {string} key The key taken from the downloaded JSON file.\n * @param {string} scope Space-delimited set of scopes.\n * @return {!OAuth2UrlFetchApp} The object for making authenticated requests.\n */\n function withServiceAccount(tokenUrl, serviceAccount, key, scope) {\n const assertionTime = new Date();\n const jwtHeader = '{\"alg\":\"RS256\",\"typ\":\"JWT\"}';\n const jwtClaimSet = {\n iss: serviceAccount,\n scope: scope,\n aud: tokenUrl,\n exp: Math.round(assertionTime.getTime() / 1000 + 3600),\n iat: Math.round(assertionTime.getTime() / 1000)\n };\n const jwtAssertion = Utilities.base64EncodeWebSafe(jwtHeader) + '.' +\n Utilities.base64EncodeWebSafe(JSON.stringify(jwtClaimSet));\n const signature = Utilities.computeRsaSha256Signature(jwtAssertion, key);\n jwtAssertion += '.' + Utilities.base64Encode(signature);\n const payload = {\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: jwtAssertion\n };\n const accessToken = authenticate_(tokenUrl, payload, null);\n return new OAuth2UrlFetchApp(accessToken);\n }\n\n scope.OAuth2 = {\n withRefreshToken: withRefreshToken,\n withClientCredentials: withClientCredentials,\n withServiceAccount: withServiceAccount,\n withPassword: withPassword\n };\n})(this);\n```"]]