如何使用Javascript从Google Api检索服务帐户OAuth2令牌?

N-a*_*ate 2 javascript google-api service-accounts google-oauth2

我需要使用Google Project服务帐户来使用JavaScript访问Google API。为了做到这一点,我需要对Google API服务器进行OAuth2认证。

我知道Google提供了可在节点服务器上使用的库(GAPI),但是我需要一个可以在其他安全JavaScript环境中使用的解决方案。

N-a*_*ate 5

此任务有两个主要部门。

  1. 配置中
  2. 编码

首先配置步骤。

  • 如果您没有Google帐户:
    1. 导航到google.com
    2. 查找并单击“登录”
    3. 点击“更多选项”
    4. 点击“创建帐户”
    5. 请按照以下步骤创建一个帐户
  • 导航到api仪表板:console.developers.google.com/apis/dashboard
  • 通过单击当前项目来选择或创建一个项目。我显示的项目称为“我的项目”在此处输入图片说明

  • 请点击 谷歌启用API和服务 并启用您打算使用的API

  • 导航至凭证部分:console.developers.google.com/apis/credentials
  • 请点击 谷歌创建凭据 然后选择“服务帐户密钥”
    • 如果您创建一个新的服务帐户,为了进行测试,请将角色设置为“项目”“所有者”。您最终将想了解google Api角色。请参阅管理角色向服务帐户授予角色
  • 确保“密钥类型”为“ Json”,然后单击“创建”。您的密钥/证书将自动下载

现在是编码部分。

  • 首先下载jsrsasign,并添加对“ jsrsasign-all-min.js”的引用。如果您愿意,可以从github下载“ jsrsasign-all-min.js”
  • 其次,使用您的cert / key(先前下载的)更新以下脚本:

    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": "service-account@...iam.gserviceaccount.com",
                "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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 测试代码时,您应该收到一个带有auth令牌的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.
    });
    
    Run Code Online (Sandbox Code Playgroud)

这是带有令牌的成功json对象的示例:

{
    "access_token": "ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgkEmo6ZlKtrvzke9C3xpwA",
    "token_type": "Bearer",
    "expires_in": 3600
}
Run Code Online (Sandbox Code Playgroud)

请注意,这种方法要求您可以从JavaScript环境中访问密钥/证书。如果此环境是公共环境,则您的api容易受到攻击。