简体   繁体   English

如何使用服务帐户的access_token发出API请求

[英]How to make API requests with an access_token for a Service Account

My end goal is to be able to retrieve place details from Google's API . 我的最终目标是能够从Google的API中检索地点的详细信息。

I need to do this as a Service Account , since this is kicked off as a background task on my server. 我需要以“ 服务帐户”的身份进行此操作,因为这是我服务器上作为后台任务启动的。 Service Accounts require you to exchange a JWT (JSON Web Token) for an access_token. 服务帐户要求您将JWT (JSON Web令牌) 交换为access_token。 I finally got that working and am receiving an access_token. 我终于得到了工作,并收到了一个access_token。 Phew. ew

Now however, I don't know what to do with this access_token. 但是现在,我不知道如何处理此access_token。

The Place Details API says that the key parameter is required, but I don't have a key. Place Details API表示key参数是必需的,但我没有密钥。 Just an access_token. 只是一个access_token。 Using that value for key or changing the name of the paramater to access_token is not working. 使用该值作为key或将参数的名称更改为access_token均无效。

Ultimately I need to be able to hit a URL like so: 最终,我需要能够像这样命中一个URL:

https://maps.googleapis.com/maps/api/place/details/json?reference={MY_REFERENCE}&sensor=false&key={MY_ACCESS_TOKEN}

How do I use my Access Token to make a request to the Google Place Detail APIs? 如何使用访问令牌向Google Place Detail API发出请求?

Update 1 更新1

Still no success, but I thought I'd post the details of my request in case there's something wrong with what I'm submitting to Google. 仍然没有成功,但是我认为我应该发布请求的详细信息,以防万一我提交给Google的内容有问题。

I'm using the JWT Ruby library , and here are the values of my claim set: 我正在使用JWT Ruby库 ,这是我的声明集的值:

{
  :iss => "54821520045-c8k5dhrjmiotbi9ni0salgf0f4iq5669@developer.gserviceaccount.com",
  :scope => "https://www.googleapis.com/auth/places",
  :aud => "https://accounts.google.com/o/oauth2/token",
  :exp => (Time.now + 3600),
  :iat => Time.now.to_i
}

Looks sane to me. 在我看来理智。

Create the service account and its credentials 创建服务帐户及其凭据

You need to create a service account and its credentials. 您需要创建一个服务帐户及其凭据。 During this procedure you need to gather three items that will be used later for the Google Apps domain-wide delegation of authority and in your code to authorize with your service account. 在此过程中,您需要收集三个项目,以后将用于Google Apps域范围内的授权,并在您的代码中用于使用服务帐户进行授权。 These three items are your service account: 这三个项目是您的服务帐户:

• Client ID. •客户端ID。

• Private key file. •私钥文件。

• Email address. • 电子邮件地址。

In order to do this, you first need a working Google APIs Console project with the Google Calendar API enabled. 为此,您首先需要一个启用了Google Calendar API的可运行的Google API控制台项目。 Follow these steps: 跟着这些步骤:

  1. Go to the Google APIs Console. 转到Google API控制台。
  2. Open your existing project or create a new project. 打开现有项目或创建一个新项目。
  3. Go to the Service section. 转到服务部分。
  4. Enable the Calendar API (and potentially other APIs you need access to). 启用日历API(以及可能需要访问的其他API)。

You can now create the service account and its credentials. 现在,您可以创建服务帐户及其凭据。 Follow these steps: 跟着这些步骤:

  1. Go to the API Access section. 转到“ API访问”部分。

  2. Create a client ID by clicking Create an OAuth 2.0 client ID... 通过单击创建OAuth 2.0客户端ID ...来创建客户端ID。

  3. Enter a product name, specify an optional logo and click Next. 输入产品名称,指定可选徽标,然后单击“下一步”。

  4. Select Service account when asked for your Application type and click Create client ID. 在询问您的应用程序类型时,选择服务帐户,然后单击创建客户端ID。

At this point you will be presented with a dialog allowing you to download the Private Key as a file (see image below). 此时,您将看到一个对话框,允许您将私钥下载为文件(请参见下图)。 Make sure to download and keep that file securely, as there will be no way to download it again from the APIs Console. 请确保安全下载并保存该文件,因为将无法从API控制台再次下载该文件。

After downloading the file and closing the dialog, you will be able to get the service account's email address and client ID. 下载文件并关闭对话框后,您将能够获取服务帐户的电子邮件地址和客户端ID。

You should now have gathered your service account's Private Key file, Client ID and email address. 现在,您应该已经收集了服务帐户的私钥文件,客户端ID和电子邮件地址。 You are ready to delegate domain-wide authority to your service account. 您已准备好将域范围的权限委派给您的服务帐户。

Delegate domain-wide authority to your service account 将域范围的权限委派给您的服务帐户

The service account that you created now needs to be granted access to the Google Apps domain's user data that you want to access. 现在需要授予您创建的服务帐户访问您要访问的Google Apps域的用户数据的权限。 The following tasks have to be performed by an administrator of the Google Apps domain: Google Apps域的管理员必须执行以下任务:

  1. Go to your Google Apps domain's control panel. 转到您的Google Apps域的控制面板。 The URL should look like: www.google.com/a/cpanel/mydomain.com 该网址应类似于:www.google.com/a/cpanel/mydomain.com

  2. Go to Advanced tools... > Manage third party OAuth Client access. 转到高级工具...>管理第三方OAuth客户端访问。

  3. In the Client name field enter the service account's Client ID. 在客户名称字段中,输入服务帐户的客户ID。

  4. In the One or More API Scopes field enter the list of scopes that your application should be granted access to (see image below). 在“一个或多个API范围”字段中,输入应授予您的应用程序访问权限的范围列表(请参见下图)。 For example if you need domain-wide access to the Google Calendar API enter: www.googleapis.com/auth/calendar.readonly 例如,如果您需要在域范围内访问Google Calendar API,请输入:www.googleapis.com/auth/calendar.readonly

  5. Click the Authorize button. 单击授权按钮。

Your service account now has domain-wide access to the Google Calendar API for all the users of your domain, and potentially the other APIs you've listed in the example above. 现在,您的服务帐户可以为您域中的所有用户在整个域范围内访问Google Calendar API,并可能在上例中列出您所列出的其他API。

Below is a description that uses a service account to access calendar data in PHP 以下是使用服务帐户访问PHP中的日历数据的说明

The general process for service account access to user calendars is a follows: 服务帐户访问用户日历的一般过程如下:

• Create the Google client •创建Google客户端

• Set the client application name •设置客户端应用程序名称

• If you already have an Access token then check to see if it is expired •如果您已经具有访问令牌,请检查它是否已过期

• If the Access token is expired then set the JWT assertion credentials and get a new token •如果访问令牌已过期,则设置JWT断言凭据并获取新令牌

• Set the client id •设置客户端ID

• Create a new calendar service object based on the Google client •基于Google客户端创建新的日历服务对象

• Retrieve the calendar events •检索日历事件

Note: You must save the Access token and only refresh it when it is about to expire otherwise you will receive an error that you have exceeded the limit for the number of access tokens in a time period for a user. 注意:您必须保存访问令牌,并且仅在访问令牌即将到期时刷新它,否则您将收到一个错误,表明您超出了用户在一段时间内访问令牌的数量限制。

Explanation of Google PHP Client library functions used: 使用的Google PHP客户端库功能的说明:

The client object has access to many parameters and methods all of the following are accessed through the client object: 客户端对象可以访问许多参数和方法,通过客户端对象可以访问以下所有内容:

Create a new client object: 创建一个新的客户端对象:

$client = new Google_Client();

Set the client application name: 设置客户端应用程序名称:

$client->setApplicationName(“My Calendar App”);

Set the client access token if you already have one saved: 如果您已经保存了一个客户端访问令牌,请设置它:

$client->setAccessToken($myAccessToken);

Check to see if the Access token has expired, there is a 30 second buffer, so this will return true if the token is set to expire in 30 seconds or less. 检查访问令牌是否已过期,是否有30秒的缓冲区,因此如果令牌设置为在30秒或更短时间内过期,则它将返回true。 The lifetime of an Access token is one hour. 访问令牌的生命周期为一小时。 The Access token is actually a JSON object which contains the time of creation, it's lifetime in seconds, and the token itself. Access令牌实际上是一个JSON对象,其中包含创建时间,生存时间(以秒为单位)以及令牌本身。 Therefore no call is made to Google as the token has all of the information locally to determine when it will expire. 因此,不会调用Google,因为令牌在本地具有所有信息来确定令牌何时到期。

$client->isAccessTokenExpired();

If the token has expired or you have never retrieved a token then you will need to set the assertion credentials in order to get an Access token: 如果令牌已过期,或者您从未检索过令牌,则需要设置断言凭据才能获取访问令牌:

$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME,array(CALENDAR_SCOPE), $key,'notasecret',' http://oauth.net/grant_type/jwt/1.0/bearer ',$email_add)); $ client-> setAssertionCredentials(新的Google_AssertionCredentials(SERVICE_ACCOUNT_NAME,array(CALENDAR_SCOPE),$ key,'notasecret',' http: //oauth.net/grant_type/jwt/1.0/bearer',$email_add));

Where:

SERVICE_ACCOUNT_NAME is the the service account email address setup earlier. SERVICE_ACCOUNT_NAME是之前设置的服务帐户电子邮件地址。

 For example:’abcd1234567890@developer.gserviceaccount.com’

CALENDAR_SCOPE is the scope setup in the Google admin interface. CALENDAR_SCOPE是Google管理界面中的范围设置。

 For example: ‘https://www.googleapis.com/auth/calendar.readonly’

$key is the content of the key file downloaded when you created the project in Google apps console. $ key是您在Google Apps控制台中创建项目时下载的密钥文件的内容。 $email_add is the Google email address of the user for whom you want to retrieve calendar data. $ email_add是您要为其检索日历数据的用户的Google电子邮件地址。

Set the client id: $client-setClientId(SERVICE_CLIENT_ID); 设置客户端ID:$ client-setClientId(SERVICE_CLIENT_ID); Where: SERVICE_CLIENT_ID is the service account client ID setup earlier. 其中:SERVICE_CLIENT_ID是先前设置的服务帐户客户端ID。 For example: 'abcd123456780.apps.googleusercontent.com' 例如:“ abcd123456780.apps.googleusercontent.com”

Create a new calendar service object: $cal = new Google_CalendarService($client); 创建一个新的日历服务对象:$ cal = new Google_CalendarService($ client);

Several options can be set for calendar retrieval I set a few of them in the code below, they are defined in the api document. 可以为日历检索设置几个选项。我在下面的代码中设置了一些选项,它们在api文档中定义。 $optEvents = array('timeMax' => $TimeMax, 'timeMin' => $TimeMin, 'orderBy' => 'startTime', 'singleEvents' => 'True'); $ optEvents = array('timeMax'=> $ TimeMax,'timeMin'=> $ TimeMin,'orderBy'=>'startTime','singleEvents'=>'True');

Get the list of calendar events and pass the above options to the call: 获取日历事件列表,并将上述选项传递给通话:

$calEvents = $cal->events->listEvents('primary', $optEvents);

Loop through the returned event list, the list is paged so we need to fetch pages until the list is exhausted: 循环浏览返回的事件列表,对页面进行分页,因此我们需要获取页面,直到列表用尽:

  foreach ($calEvents->getItems() as $event) {
// get event data
$Summary = $event->getSummary();
$description = $event->getDescription();
$pageToken = $calEvents->getNextPageToken();
            if ($pageToken) { // if we got a token the fetch the next page of events.
                    $optParams = array('pageToken' => $pageToken);
                    $calEvents = $cal->events->listEvents('primary', $optParams);
            } else {
                    break;
            }

} }

Get the Access token: 获取访问令牌:

$myAccessToken=$client->getAccessToken(); $ myAccessToken = $ client-> getAccessToken();

Save the access token to your permanent store for the next time. 下次将访问令牌保存到永久存储中。

The language isn't important php, ruby, .net, java the process is the same. 语言并不重要php,ruby,.net,java的过程是相同的。 The api's console shows the Places API as supporting service accounts so it should be possible to access it. api的控制台将Places API显示为支持服务帐户,因此应该可以访问它。

As far as using the token please have a look at https://code.google.com/p/google-api-ruby-client/ code as the usage is clearly defined in the code repository. 至于使用令牌,请查看https://code.google.com/p/google-api-ruby-client/代码,因为用法已在代码存储库中明确定义。 Doesn't make any difference if the access token is for a service account or a single user the process for using the token is the same. 如果访问令牌是用于服务帐户或单个用户的,则使用令牌的过程是相同的。 See the section titled "Calling a Google API" in the following link: https://developers.google.com/accounts/docs/OAuth2InstalledApp 请参见以下链接中标题为“调用Google API”的部分: https : //developers.google.com/accounts/docs/OAuth2InstalledApp

The access token is sent in the http authorization header along with the request.For a calendar request it would look something like the following: GET /calendar/v3/calendars/primary HTTP/1.1 Host: www.googleapis.com Content-length: 0 Authorization: OAuth ya29.AHES6ZTY56eJ0LLHz3U7wc-AgoKz0CXg6OSU7wQA 访问令牌与请求一起发送到http授权标头中。对于日历请求,它看起来类似于以下内容:GET / calendar / v3 / calendars / primary HTTP / 1.1主机:www.googleapis.com内容长度: 0授权:OAuth ya29.AHES6ZTY56eJ0LLHz3U7wc-AgoKz0CXg6OSU7wQA

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM