如何从(非Web)python客户端访问经过身份验证的Google App Engine服务?

dal*_*ane 52 python authentication google-app-engine web-services

我有一个Google App Engine应用程序 - http://mylovelyapp.appspot.com/ 它有一个页面 - mylovelypage

目前,页面就是这样 self.response.out.write('OK')

如果我在我的计算机上运行以下Python:

import urllib2
f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage")
s = f.read()
print s
f.close()
Run Code Online (Sandbox Code Playgroud)

它打印"OK"

问题是如果我login:required在应用程序的yaml中添加到此页面

然后打印出Google帐户登录页面的HTML

我尝试过"正常"的身份验证方法.例如

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()

auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None,
                          uri='http://mylovelyapp.appspot.com/mylovelypage',
                          user='billy.bob@gmail.com',
                          passwd='billybobspasswd')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
Run Code Online (Sandbox Code Playgroud)

但它没有任何区别 - 我仍然得到登录页面的HTML.

我已经尝试了Google的ClientLogin auth API,但我无法让它工作.

h = httplib2.Http()

auth_uri = 'https://www.google.com/accounts/ClientLogin'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
myrequest = "Email=%s&Passwd=%s&service=ah&source=DALELANE-0.0" % ("billy.bob@gmail.com", "billybobspassword")
response, content = h.request(auth_uri, 'POST', body=myrequest, headers=headers)

if response['status'] == '200':
    authtok = re.search('Auth=(\S*)', content).group(1)

    headers = {}
    headers['Authorization'] = 'GoogleLogin auth=%s' % authtok.strip()
    headers['Content-Length'] = '0'

    response, content = h.request("http://mylovelyapp.appspot.com/mylovelypage", 
                                  'POST', 
                                  body="", 
                                  headers=headers)

    while response['status'] == "302":        
        response, content = h.request(response['location'], 'POST', body="", headers=headers) 

    print content
Run Code Online (Sandbox Code Playgroud)

我似乎能够正确地获得一些令牌,但是当我调用'mylovelypage'时尝试在标题中使用它仍然只是返回登录页面的HTML.:-(

有人可以帮忙吗?

我可以使用GData客户端库来做这种事情吗?从我读过的内容来看,我认为它应该能够访问App Engine应用程序,但我还没有更成功地为App Engine工作的身份验证工作

任何指向样本,文章,甚至只是我应该寻找的关键词以便让我开始的指针都将非常感激.

谢谢!

Nic*_*son 39

appcfg.py,将数据上传到App Engine的工具必须做到这一点,以便通过App Engine服务器进行身份验证.相关功能被抽象为appengine_rpc.py.简而言之,解决方案是:

  1. 使用Google ClientLogin API获取身份验证令牌.appengine_rpc.py在_GetAuthToken中执行此操作
  2. 将身份验证令牌发送到App Engine应用程序上的特殊URL.然后该页面返回一个cookie和一个302重定向.忽略重定向并存储cookie.appcfg.py在_GetAuthCookie中执行此操作
  3. 在将来的所有请求中使用返回的cookie.

您可能还想查看_Authenticate,以了解appcfg如何处理来自ClientLogin和_GetOpener的各种返回代码,以查看appcfg如何创建不遵循HTTP重定向的urllib2 OpenerDirector.或者,您实际上只需批量使用AbstractRpcServer和HttpRpcServer类,因为它们几乎可以满足您的所有需求.

  • https://developers.google.com/accounts/docs/AuthForInstalledApps表示截至2012年4月已弃用ClientLogin.是否存在Oauth2等效项? (6认同)

dal*_*ane 34

感谢Arachnid的答案 - 它按照建议工作

这里是代码的简化副本,以防下一个人尝试!

import os
import urllib
import urllib2
import cookielib

users_email_address = "billy.bob@gmail.com"
users_password      = "billybobspassword"

target_authenticated_google_app_engine_uri = 'http://mylovelyapp.appspot.com/mylovelypage'
my_app_name = "yay-1.0"



# we use a cookie to authenticate with Google App Engine
#  by registering a cookie handler here, this will automatically store the 
#  cookie returned when we use urllib2 to open http://currentcost.appspot.com/_ah/login
cookiejar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(opener)

#
# get an AuthToken from Google accounts
#
auth_uri = 'https://www.google.com/accounts/ClientLogin'
authreq_data = urllib.urlencode({ "Email":   users_email_address,
                                  "Passwd":  users_password,
                                  "service": "ah",
                                  "source":  my_app_name,
                                  "accountType": "HOSTED_OR_GOOGLE" })
auth_req = urllib2.Request(auth_uri, data=authreq_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_body = auth_resp.read()
# auth response includes several fields - we're interested in 
#  the bit after Auth= 
auth_resp_dict = dict(x.split("=")
                      for x in auth_resp_body.split("\n") if x)
authtoken = auth_resp_dict["Auth"]

#
# get a cookie
# 
#  the call to request a cookie will also automatically redirect us to the page
#   that we want to go to
#  the cookie jar will automatically provide the cookie when we reach the 
#   redirected location

# this is where I actually want to go to
serv_uri = target_authenticated_google_app_engine_uri

serv_args = {}
serv_args['continue'] = serv_uri
serv_args['auth']     = authtoken

full_serv_uri = "http://mylovelyapp.appspot.com/_ah/login?%s" % (urllib.urlencode(serv_args))

serv_req = urllib2.Request(full_serv_uri)
serv_resp = urllib2.urlopen(serv_req)
serv_resp_body = serv_resp.read()

# serv_resp_body should contain the contents of the 
#  target_authenticated_google_app_engine_uri page - as we will have been 
#  redirected to that page automatically 
#
# to prove this, I'm just gonna print it out
print serv_resp_body
Run Code Online (Sandbox Code Playgroud)

  • 这个答案已经过时了:https://developers.google.com/identity/protocols/AuthForInstalledApps (2认同)