本文介绍了如何使用Javascript从Google Api检索服务帐户OAuth2令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Google Projects服务帐户来使用JavaScript访问Google API.为此,我需要对Google API服务器进行OAuth2认证,以获取身份验证令牌.

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

解决方案

此任务分为两个主要部分.

  1. 配置
  2. 编码

首先执行配置步骤.

  • 如果您没有Google帐户:

    1. 导航到

    2. 单击,并启用您打算使用的API

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

现在是编码部分.

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

     函数postJWT(jwt,回调){var xhttp = new XMLHttpRequest();xhttp.onreadystatechange = function(){如果(this.readyState == 4){if(this.status == 200&&回调){回调(this.responseText);返回;}如果(控制台)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);}函数getCert(){var cert =//您的json密钥(先前下载)在此处{"type":"service_account","project_id":"proj ..","private_key_id":"e18 ..","private_key":"-----开始私钥----- \ nMII .. == \ n -----结束私钥----- \ 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"};退货证明书;}函数getJWT(){var cert = getCert();var key = KEYUTIL.getKey(cert.private_key);var headers = {" alg:" RS256," typ:" JWT};发出的var = 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":已发布+ 3600,"iat":已发布};var jwt = KJUR.jws.JWS.sign(headers.alg,headers,JSON.stringify(claims),key);返回jwt;} 

  • 在测试代码时,您应该收到一个带有auth令牌的json对象.您可以像这样测试实现:

      postJWT(getJWT(text),function(){让令牌= JSON.parse(response).access_token;//使用令牌在此处调用您的api.//最多重复使用令牌1小时.}); 

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

  {"access_token":"ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgE2"token_type":承载者","expires_in":3600} 

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

I need to use a google projects service account to access google API using JavaScript. In order to do this I need to OAuth2 to google API servers to get an auth token.

I understand that Google provides a library (GAPI) for use on node servers, but I need a solution that will work in other secure JavaScript environments.

解决方案

There are two major divisions to this task.

  1. Configuring
  2. Coding

First the Configuration steps.

  • If you don't have a google account:

    1. Navigate to google.com
    2. Find and Click "Sign In"
    3. Click "More Options"
    4. Click "Create Account"
    5. Follow the steps to create an account

  • Navigate to the api dashboard: console.developers.google.com/apis/dashboard
  • Select or create a project by clicking on the current project. The project I have showing is called "My Project"

  • Click and enable those API you plan to work with

  • navigate to the credentials section: console.developers.google.com/apis/credentials
  • Click and select "Service account key"
  • Ensure "Key Type" is "Json" and click "Create". You're key/cert will automatically download

Now for the Coding portion.

  • First download jsrsasign and add reference to "jsrsasign-all-min.js". If you want you can download just "jsrsasign-all-min.js" from github
  • Second update the following script with your cert/key (downloaded earlier):

    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;
    }
    

  • When you test your code you should receive a json object back with an auth token. You can test your implementation like so:

    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.
    });
    

Here is an example successful json object with token:

{
    "access_token": "ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgkEmo6ZlKtrvzke9C3xpwA",
    "token_type": "Bearer",
    "expires_in": 3600
}

Please note that this approach requires that the key/cert be accessible from your javascript environment. If this environment is public your api is vulnerable.

这篇关于如何使用Javascript从Google Api检索服务帐户OAuth2令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 15:51
查看更多