简体   繁体   English

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

[英]How can I retrieve a service account OAuth2 token from Google Api with Javascript?

I need to use a google projects service account to access google API using JavaScript. 我需要使用Google Project服务帐户来使用JavaScript访问Google API。 In order to do this I need to OAuth2 to google API servers to get an auth token. 为了做到这一点,我需要对Google API服务器进行OAuth2认证。

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

There are two major divisions to this task. 此任务有两个主要部门。

  1. Configuring 配置
  2. Coding 编码

First the Configuration steps. 首先配置步骤。

  • If you don't have a google account: 如果您没有Google帐户:
    1. Navigate to google.com 导航到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 导航到api仪表板: 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 点击 谷歌启用API和服务 and enable those API you plan to work with 并启用您打算使用的API

  • navigate to the credentials section: console.developers.google.com/apis/credentials 导航至凭证部分: console.developers.google.com/apis/credentials
  • Click 点击 谷歌创建凭据 and select "Service account key" 然后选择“服务帐户密钥”
  • Ensure "Key Type" is "Json" and click "Create". 确保“密钥类型”为“ Json”,然后单击“创建”。 You're key/cert will automatically download 您的密钥/证书将自动下载

Now for the Coding portion. 现在是编码部分。

  • First download jsrsasign and add reference to "jsrsasign-all-min.js". 首先下载jsrsasign,并添加对“ jsrsasign-all-min.js”的引用。 If you want you can download just "jsrsasign-all-min.js" from github 如果您愿意,可以从github下载“ jsrsasign-all-min.js”
  • Second update the following script with your cert/key (downloaded earlier): 其次,使用您的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; } 
  • When you test your code you should receive a json object back with an auth token. 测试代码时,您应该收到一个带有auth令牌的json对象。 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: 这是带有令牌的成功json对象的示例:

{
    "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. 请注意,这种方法要求您可以从JavaScript环境中访问密钥/证书。 If this environment is public your api is vulnerable. 如果此环境是公共环境,则您的api容易受到攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Google OAuth2 javascript获取刷新令牌? - How to get a refresh Token with Google OAuth2 javascript? 使用 Javascript 解码 Google Oauth2 访问令牌 - Decode Google Oauth2 Access Token with Javascript 带有JavaScript的Google OAuth2刷新令牌 - Google OAuth2 Refresh Token with JavaScript 如何通过Google云端硬盘Javascript OAuth2 API创建Google表格文档? - How do I create a Google Sheets document via the Google Drive Javascript OAuth2 API? Google通过OAuth2身份验证从JavaScript客户端联系API问题 - Google contacts API problems from JavaScript client with OAuth2 authentication 带有服务帐户Oauth2的Google云端硬盘选择器(p12文件)Javascript - Google Drive Picker with Service Account Oauth2 (p12 file) Javascript 我如何在Jersey Jersey REST Web服务中使用Google OAuth2 - How can i use google OAuth2 in my Jersey REST Web Service 如何访问谷歌 Oauth2 护照中的个人资料信息? - How can I access profile information in google Oauth2 passport? 如何从Trello API检索令牌 - How can I retrieve a token from Trello API 如何获取 Google 服务帐户访问令牌 javascript - How to obtain Google service account access token javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM