从Google Apps脚本访问经过身份验证的Google Cloud Endpoints API

时间:2022-05-27 04:32:19

I'm trying to pull some data into a Google sheets spreadsheet from an API that's been built using Google Cloud Endpoints. Here is the API declaration:

我正在尝试将一些数据从使用Google Cloud Endpoints构建的API中提取到Google表格电子表格中。这是API声明:

@Api(
        name = "myendpoint", 
        namespace = 
            @ApiNamespace
                (
                    ownerDomain = "mydomain.com", 
                    ownerName = "mydomain.com", 
                    packagePath = "myapp.model"
                ),
         scopes = {SCOPES},
         clientIds = {ANDROID_CLIENT_ID, WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID},
         audiences = {WEB CLIENT_ID}
)

The method I'm trying to access has authentication enabled by means of the user parameter in the API declaration:

我尝试访问的方法通过API声明中的user参数启用了身份验证:

@ApiMethod(name = "ping", httpMethod = HttpMethod.GET, path = "ping")
public StringResponse getPing(User user) throws OAuthRequestException {

    CheckPermissions(user);//throws an exception if the user is null or doesn't have the correct permissions

    return new StringResponse("pong");
}

This works fine when using the generated client libraries or the gapi js library. However AFAIK I can't use those js libraries in Apps Script.

这在使用生成的客户端库或gapi js库时工作正常。但是AFAIK我不能在Apps脚本中使用那些js库。

I've got an OAuth2 flow working using the apps-script-oauth2 library from here, and I'm pretty much using the default setup for creating the service

我从这里使用apps-script-oauth2库有一个OAuth2流程,我几乎使用默认设置来创建服务

function getService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  return OAuth2.createService(SERVICE_NAME)

  // Set the endpoint URLs, which are the same for all Google services.
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')

  // Set the client ID and secret, from the Google Developers Console.
  .setClientId(CLIENT_ID)
  .setClientSecret(CLIENT_SECRET)

  // Set the name of the callback function in the script referenced
  // above that should be invoked to complete the OAuth flow.
  .setCallbackFunction('ruggedAuthCallback')

  // Set the property store where authorized tokens should be persisted.
  .setPropertyStore(PropertiesService.getUserProperties())

  // Set the scopes to request (space-separated for Google services).
  .setScope(SCOPES)

  // Below are Google-specific OAuth2 parameters.

  // Sets the login hint, which will prevent the account chooser screen
  // from being shown to users logged in with multiple accounts.
  .setParam('login_hint', Session.getActiveUser().getEmail())

  // Requests offline access.
  .setParam('access_type', 'offline')

  // Forces the approval prompt every time. This is useful for testing,
  // but not desirable in a production application.
  .setParam('approval_prompt', 'auto')

  //.setParam('include_granted_scopes', 'true');
}

These are my methods for accessing the APIs

这些是我访问API的方法

function getDriveDocs() {
  return executeApiMethod('https://www.googleapis.com/drive/v2/','files?maxResults=10');
}

function pingServer(){
  return executeApiMethod('https://myapp.appspot.com/_ah/api/myendpoint/v1/','ping');
}

function executeApiMethod(apiUrl, method)
{
  //var url = ;
  var url = apiUrl + method;
  var service = getRuggedService();
  return UrlFetchApp.fetch(url, {
    'muteHttpExceptions': true,
    'method': 'get',
    'headers': {
      Authorization: 'Bearer ' + service.getAccessToken()
    }
  });
}

The getDriveDocs() method works perfectly, so I know my auth flow is working correctly. Also, if I call an unauthenticated method in my API I get the correct response. However, when I call the authenticated 'ping' method, the 'user' parameter is always null. Am I missing something in the fetch call? Everything I've read so far seems to suggest that setting

getDriveDocs()方法工作正常,所以我知道我的auth流程正常工作。此外,如果我在API中调用未经身份验证的方法,我会得到正确的响应。但是,当我调用经过身份验证的“ping”方法时,“user”参数始终为null。我在fetch调用中遗漏了什么?到目前为止,我所阅读的所有内容似乎都暗示了这一点

Authorization: 'Bearer ' + service.getAccessToken()

should be enough.

应该够了。

Any help would be much appreciated!

任何帮助将非常感激!

1 个解决方案

#1


0  

This turned out to be a simple mistake - I had created a new oauth2 credential in the google dev console and had not added the new client id to the API declaration. Here is the working API declaration:

这被证明是一个简单的错误 - 我在google开发者控制台中创建了一个新的oauth2凭证,并且没有在API声明中添加新的客户端ID。这是工作API声明:

@Api(
        name = "myendpoint", 
        namespace = 
            @ApiNamespace
                (
                    ownerDomain = "mydomain.com", 
                    ownerName = "mydomain.com", 
                    packagePath = "myapp.model"
                ),
         scopes = {SCOPES},
         clientIds = {ANDROID_CLIENT_ID, WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID, GAPPS_CLIENT_ID},
         audiences = {WEB CLIENT_ID}
    )

#1


0  

This turned out to be a simple mistake - I had created a new oauth2 credential in the google dev console and had not added the new client id to the API declaration. Here is the working API declaration:

这被证明是一个简单的错误 - 我在google开发者控制台中创建了一个新的oauth2凭证,并且没有在API声明中添加新的客户端ID。这是工作API声明:

@Api(
        name = "myendpoint", 
        namespace = 
            @ApiNamespace
                (
                    ownerDomain = "mydomain.com", 
                    ownerName = "mydomain.com", 
                    packagePath = "myapp.model"
                ),
         scopes = {SCOPES},
         clientIds = {ANDROID_CLIENT_ID, WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID, GAPPS_CLIENT_ID},
         audiences = {WEB CLIENT_ID}
    )