0
我需要使用Google项目服务帐户才能使用JavaScript访问Google API。为了做到这一点,我需要OAuth2谷歌API服务器来获得一个身份验证令牌。如何从Google Api使用Javascript检索服务帐户OAuth2令牌?
我知道Google提供了一个用于节点服务器的库(GAPI),但我需要一个能在其他安全JavaScript环境中工作的解决方案。
我需要使用Google项目服务帐户才能使用JavaScript访问Google API。为了做到这一点,我需要OAuth2谷歌API服务器来获得一个身份验证令牌。如何从Google Api使用Javascript检索服务帐户OAuth2令牌?
我知道Google提供了一个用于节点服务器的库(GAPI),但我需要一个能在其他安全JavaScript环境中工作的解决方案。
这个任务有两大部门。
首先配置步骤。
现在为编码部分。
二更新您的证书/密钥(先前下载)下面的脚本:
function postJWT(jwt, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200 && callback) {
callback(this.responseText);
return;
}
if (console) console.log(this.responseText);
}
};
var parameters = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") + "&assertion=" + encodeURIComponent(jwt);
xhttp.open("POST", "https://www.googleapis.com/oauth2/v4/token", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(parameters);
}
function getCert() {
var cert = //your json key (downloaded earlier) goes here
{
"type": "service_account",
"project_id": "proj..",
"private_key_id": "e18..",
"private_key": "-----BEGIN PRIVATE KEY-----\nMII..==\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "5761..",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/..service-account%40...iam.gserviceaccount.com"
};
return cert;
}
function getJWT() {
var cert = getCert();
var key = KEYUTIL.getKey(cert.private_key);
var headers = { "alg": "RS256", "typ": "JWT" };
var issued = Math.floor(new Date().getTime()/1000);
var claims = {
"iss": cert.client_email,
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"aud": "https://www.googleapis.com/oauth2/v4/token",
"exp": issued + 3600,
"iat": issued
};
var jwt = KJUR.jws.JWS.sign(headers.alg, headers, JSON.stringify(claims), key);
return jwt;
}
当你测试你的代码你应该收到一个带有认证令牌的json对象。您可以测试你的实现像这样:
postJWT(getJWT(text), function(){
let token = JSON.parse(response).access_token;
//Do your api calls here using the token.
//Reuse the token for up to 1 hour.
});
这里是一个令牌的例子成功的JSON对象:
{
"access_token": "ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgkEmo6ZlKtrvzke9C3xpwA",
"token_type": "Bearer",
"expires_in": 3600
}
请注意,这种方法要求的关键/证书从访问你的JavaScript环境。如果这个环境是公开的,你的api就很脆弱。
嗨,我想知道如何结合调用谷歌分析api – Elvira
@Elvira我已经更新了代码,以反映你应该放置你的API调用。如果您需要使用令牌设置api调用的帮助,请提出一个新问题并标记我或将其链接到此处,以便我可以提供帮助。我会尽力留意它。 –