我在Google App Engine上有两个应用程序,都在同一个帐户下运行,其中一个通过HTTPS调用另一个提供的服务。要确保只允许第一个应用程序调用第二个应用程序,推荐的方法是什么?
或者,有没有办法指定给定的端点只能由运行在同一GAE帐户下的应用程序调用?
发布于 2012-11-06 21:16:33
让您的应用程序检查“X-Appengine-Inbound-Appid”标头,并确保应用程序ID正确。仅当请求由另一个Google App Engine应用程序发出且用户无法修改时,此标头才存在。
如果您使用的是Python,则可以执行以下操作:
import webapp2
AUTHORIZED_APPS = ('my-first-app', 'my-other-app')
class MyHandler(webapp2.RequestHandler):
def dispatch(self):
app_id = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if app_id in AUTHORIZED_APPS:
super(MyHandler, self).dispatch()
else:
self.abort(403)对于头中没有X-Appengine-Inbound-Appid的任何请求,这将引发一个403。
此外,当使用urlfetch从一个应用程序向另一个应用程序发出请求时,请确保设置了follow_redirects=False,否则不会添加标头。
发布于 2016-03-31 01:28:52
正如其他人所指出的,依靠标头X-Appengine-Inbound-Appid被填写是最简单的解决方案。我最近遇到了一个类似的问题,但我无法使用X-Appengine-Inbound-Appid,因为URLFetch不可用(GAE Node.js)。以下是如何使用通过OAuth进行身份验证的服务帐户来解决此问题。
在发送方,您需要设置一个服务帐户:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
然后,在该应用程序中,您需要获取服务帐户凭据:https://developers.google.com/identity/protocols/application-default-credentials
然后,您可以使用凭据创建一个authClient,用它来发送请求。您需要在authClient中添加一个OAuth作用域。最合乎逻辑的选择是https://www.googleapis.com/auth/userinfo.email。这将使收件人能够获得发件人的服务帐户的电子邮件地址。https://developers.google.com/identity/protocols/googlescopes
下面是让它在(发送者)Node.js中工作的代码:
process.env.GOOGLE_APPLICATION_CREDENTIALS = <PATH TO CREDENTIALS FILE>
google.auth.getApplicationDefault((err, authClient) => {
if (err) {
console.log("Failed to get default credentials: ", String(err));
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/userinfo.email'
]);
}
auth_client.request({
url: <RECEIVER URL>,
method: "GET"
}, (error, result, response) => {
// Process response
});
});然后,在接收方,您需要验证电子邮件地址是否与发送方服务帐户的电子邮件地址匹配。当在本地调用应用程序引擎时,OAuth请求没有正确地进行身份验证,所以如果你想在本地测试,你将不得不自己做一个url获取来验证请求。
Receiver Python:
scope = "https://www.googleapis.com/auth/userinfo.email"
allowed_users = set([
"<SENDER SERVICE ACCOUNT EMAIL>"
])
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
class MyHandler(webapp2.RequestHandler):
def get(self, clientId):
user = self.get_current_user()
if user in allowed_users:
# Do whatever you wanted
def get_current_user(self):
if IS_DEV:
token = self.request.headers.get("Authorization")[len("Bearer "):]
response = urlfetch.fetch(
"https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=%s" % token
)
return json.loads(response.content)["email"]
else:
return oauth.get_current_user(scope)发布于 2012-11-06 16:48:25
你可能想看看App Engine的Application Identity服务。
https://stackoverflow.com/questions/13245540
复制相似问题