我正在开发用 Python 编写并使用 Endpoints API 的 Google App Engine 应用程序。同时,我正在编写一个 Chrome 扩展程序来与 Endpoints API 交互。我在 Endpoints API 和授权方面遇到了很多问题。目前,这是我的设置:
端点 API (Python)
from google.appengine.ext import endpoints
from protorpc import message_types
from protorpc import remote
ALLOWED_CLIENT_IDS = ['client_id_from_google_api_console',
endpoints.API_EXPLORER_CLIENT_ID]
@endpoints.api(name='my_api',version='v1', description='My API',
allowed_client_ids=ALLOWED_CLIENT_IDS)
class MyApi(remote.Service):
@endpoints.method(message_types.VoidMessage, DeviceListResponse,
name='user.device.list', path='user/device/list',
http_method='GET')
def user_device_list(self, request):
current_user = endpoints.get_current_user()
if current_user is None:
raise endpoints.UnauthorizedException('You must authenticate first.')
if current_user.user_id() is None:
raise endpoints.NotFoundException("Your user id was not found.")
return DeviceListResponse(devices=[]) #Hypothetically return devices
api_service = endpoints.api_server([MyApi], restricted=False)
谷歌 API 控制台
JS 来源包括:chrome-extensions://chrome_app_id
铬扩展 (JS)
var apiRoot = "https://my_app_id.appspot.com/_ah/api";
var clientID = "client_id_from_google_api_console";
var oauthScopes = ["https://www.googleapis.com/auth/userinfo.email"];
var responseType = "token id_token";
//Helper method to log to the console
function l(o){console.log(o);}
function oauthSignin(mode) {
gapi.auth.authorize({client_id: clientID, scope: oauthScopes,
immediate: mode, response_type: responseType}, function() {
var request = gapi.client.oauth2.userinfo.get();
request.execute(function(resp) {
authenticated = !resp.code;
if(authenticated) {
var token = gapi.auth.getToken();
token.access_token = token.id_token;
gapi.auth.setToken(token);
l("Successfully authenticated. Loading device list");
gapi.client.my_api.user.device.list({}).execute(function(resp) {
if(resp.code) {
l("Response from device list: " + resp.message);
}
l(resp);
});
}
});
});
}
//This get's called when the page and js library has loaded.
function jsClientLoad() {
l("JS Client Libary loaded. Now loading my_api and oauth2 APIs.");
var apisToLoad;
var callback = function() {
if (--apisToLoad == 0) {
l("APIs have loaded.")
oauthSignin(true);
} else {
l("Waiting for " + apisToLoad + " API" + (apisToLoad>1?"s":"") + " to load.");
}
}
apisToLoad = 2; // must match number of calls to gapi.client.load()
gapi.client.load('my_api', 'v1', callback, apiRoot);
gapi.client.load('oauth2', 'v2', callback);
}
结果
现在我已经展示了我的代码的主要部分(请注意,我必须稍微更改它以使其有意义而不上传整个代码),如果我转到 Google API Explorer 并运行该方法,我会得到 200 响应。如果我在 Chrome 扩展程序中运行它,我会收到一个 404 代码,并显示消息“找不到您的用户 ID。”。