oauth 谷歌使用python [英] oauth google using python

查看:35
本文介绍了oauth 谷歌使用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对网络编程还很陌生.我想在这里从头开始.我试图搜索网络,但最终完全糊涂了.现在我想学习的是如何通过 python 脚本验证谷歌帐户.任何人都可以向我提供代码片段或任何示例.

非常感谢.

解决方案

在过去几周的几次尝试失败后,我花了一整天的时间编写代码.这只会让您迈出第一步,但它不需要任何外部库.是的,我知道 OP 已经快两年了,但从我看来,它仍然需要完成.

<预><代码>#!/usr/bin/python'演示 Google OAuth'导入系统、操作系统、urllib、urllib2、时间、httplib导入 hmac、hashlib、随机、re、base64参数 = {'oauth_consumer_key': os.getenv('OAUTH_CONSUMER_KEY') 或 'anonymous','oauth_signature_method': 'HMAC-SHA1','oauth_signature': '','oauth_timestamp': os.getenv('OAUTH_TIMESTAMP') 或 '%d' % time.time(),'oauth_nonce': os.getenv('OAUTH_NONCE') 或 '%x' % random.getrandbits(64),'oauth_version': '1.0','oauth_callback': os.getenv('OAUTH_CALLBACK') 或 'callback',}范围 = {'范围':'https://www.google.com/calendar/feeds/'}SECRET = os.getenv('OAUTH_CONSUMER_SECRET') 或 '匿名'def google_oauth():'OAuthGetRequestToken、OAuthAuthorizeToken、OAuthGetAccessToken'request_token = get_request_token()返回 request_tokendef get_request_token():'向 Google 索取请求令牌'url = 'https://www.google.com/accounts/OAuthGetRequestToken'token_secret = '' # 我们还没有令牌秘密参数['oauth_signature'] = sign('&'.join((SECRET, token_secret)),'&'.join(map(urlencode, ('GET', url, parameters('signing')))))body = urllib.urlencode(SCOPE)request = urllib2.Request(url + '?' + body)request.add_header('Authorization', 'OAuth' + parameters('header'))开瓶器 = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel = 1))响应 = opener.open(request)回复 = response.read()response.close()回覆定义字节编码(匹配):'与 re.sub 一起使用'返回 '​​%%%02X' % ord(match.group())def urlencode(string):未保留 = ALPHA、DIGIT、'-'、'.'、'_'、'~'"return re.sub(re.compile('[^0-9A-Za-z._~-]'),byte_encode, string.encode('utf8'))定义符号(秘密,文本):打印 >>sys.stderr, 'signature base string: "%s", secret: %s' % (代表(文本),代表(秘密))摘要 = hmac.new(secret, text, hashlib.sha1).digest()返回 urlencode(base64.encodestring(digest).rstrip())def base64string(hexstring):重新编码 = urlencode(base64.encodestring(hexstring.decode('hex')).rstrip())打印 >>sys.stderr, 'recoded:', 重新编码返回记录定义参数(格式):如果格式=='标题':格式化 = ', '.join(['%s="%s"' % (key, value)对于键,PARAMETERS.items()] 中的值elif 格式 == '签名':格式化 = '&'.join(sorted(['%s=%s' % (key,urlencode(value.encode('utf8'))) 为键,值 (PARAMETERS.items() + SCOPE.items()) 如果密钥不在 ['oauth_signature']]))#print >>sys.stderr,格式化,格式化返回格式化def hmac_sha1_test():'来自 tools.ietf.org/html/rfc2202'assert sign('\x0b' * 20, 'Hi There') == base64string('b617318655057264e28bc0b6fb378c8ef146be00')assert sign('Jefe', '你想要什么?') == base64string('effcdf6ae5eb2fa2d27416d5f184df9c259a7c79')assert sign('\xaa' * 20, '\xdd' * 50) == base64string('125d7342b9ac11cd91a39af48aa17b4f63f175d3')# 最后一次测试来自 http://oauth.net/core/1.0/#rfc.section.9.1.1, app.A.5.2断言符号('kd94hf93k423kf44&pfkkdhi9sl3r4s00','GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26' + \'oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D' + \'kllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26' + \'oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26' + \'oauth_version%3D1.0%26size%3Doriginal') == urlencode('tR3+Ty81lMeYAr/Fid0kMTYa/WM=')返回真如果 __name__ == '__main__':命令 = os.path.splitext(os.path.basename(sys.argv[0]))[0]打印 eval(command)(*sys.argv[1:])

将其另存为 google_oauth.py,您可以像这样链接到它:

ln -s google_oauth.py hmac_sha1_test.py

以测试任何子例程.结合环境变量的使用,您可以将您的结果与 Google 的 OAuth Playground(这里的其他人提供链接)的结果进行比较,看看您哪里出错了.我发现脚本有很多问题.可能还有更多.但是,如果您调用 ./google_oauth.py,您应该会看到如下内容:

<前>jcomeau@intrepid:~/rentacoder/marchie$ ./google_oauth.py签名基本字符串:'GET&HTTPS%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dcallback%26oauth_consumer_key%3Danonymous%26oauth_nonce%3Da64720fda018906b%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1302253695%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fcalendar%252Ffeeds%252F'",秘密:'匿名&'发送:'GET/accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\n连接: 关闭\r\n授权: OAuth oauth_nonce="a64720fda018906b", oauth_timestamp="1302253695", oauth_consumer_key="anonymous", oauth_signature_method="HMAC-Jothgts", oauth_signature_method="HMAC-Jothgs0gs1", FXc1augs7augs1",, oauth_callback="callback"\r\n用户代理:Python-urllib/2.6\r\n\r\n'回复: 'HTTP/1.1 200 OK\r\n'标题:内容类型:文本/纯文本;字符集=UTF-8标题: 日期: 2011 年 4 月 8 日星期五 09:08:20 GMT标题: 到期: 2011 年 4 月 8 日星期五 09:08:20 GMT标头:缓存控制:私有,最大年龄= 0标头:X-Content-Type-Options:nosniff标头:X-XSS-保护:1;模式=块标题:内容长度:118标头:服务器:GSE标题:连接:关闭oauth_token=4%2FfvSIWW9WBHXa_CjInpOf4FdNYhCj&oauth_token_secret=qhB1EGIKjL1pG9POF2ZOcQk3&oauth_callback_confirmed=true

i am fairly new to programming for web. and i want to start from scratch here. i tried to search the net but ended up completely confused. now what i want to learn is how to authenticate a google account through a python script. can anyone please provide me with a code fragment or any example.

thanks a lot in advance.

解决方案

I spent a whole day on coding this, after several failed attempts over the past few weeks. This only gets you as far as the first step, but it does so without any external libraries. And yes, I know it's close to two years after the OP, but from what I could see it still needed to be done.


#!/usr/bin/python
'demo Google OAuth'
import sys, os, urllib, urllib2, time, httplib
import hmac, hashlib, random, re, base64
PARAMETERS = {
 'oauth_consumer_key': os.getenv('OAUTH_CONSUMER_KEY') or 'anonymous',
 'oauth_signature_method': 'HMAC-SHA1',
 'oauth_signature': '',
 'oauth_timestamp': os.getenv('OAUTH_TIMESTAMP') or '%d' % time.time(),
 'oauth_nonce': os.getenv('OAUTH_NONCE') or '%x' % random.getrandbits(64),
 'oauth_version': '1.0',
 'oauth_callback': os.getenv('OAUTH_CALLBACK') or 'callback',
}
SCOPE = {'scope': 'https://www.google.com/calendar/feeds/'}
SECRET = os.getenv('OAUTH_CONSUMER_SECRET') or 'anonymous'
def google_oauth():
 'OAuthGetRequestToken, OAuthAuthorizeToken, OAuthGetAccessToken'
 request_token = get_request_token()
 return request_token
def get_request_token():
 'ask Google for a request token'
 url = 'https://www.google.com/accounts/OAuthGetRequestToken'
 token_secret = ''  # we don't have a token secret yet
 PARAMETERS['oauth_signature'] = sign('&'.join((SECRET, token_secret)),
  '&'.join(map(urlencode, ('GET', url, parameters('signing')))))
 body = urllib.urlencode(SCOPE)
 request = urllib2.Request(url + '?' + body)
 request.add_header('Authorization', 'OAuth ' + parameters('header'))
 opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel = 1))
 response = opener.open(request)
 reply = response.read()
 response.close()
 return reply
def byte_encode(match):
 'for use with re.sub'
 return '%%%02X' % ord(match.group())
def urlencode(string):
 "unreserved = ALPHA, DIGIT, '-', '.', '_', '~'"
 return re.sub(re.compile('[^0-9A-Za-z._~-]'),
  byte_encode, string.encode('utf8'))
def sign(secret, text):
 print >>sys.stderr, 'signature base string: "%s", secret: %s' % (
  repr(text), repr(secret))
 digest = hmac.new(secret, text, hashlib.sha1).digest()
 return urlencode(base64.encodestring(digest).rstrip())
def base64string(hexstring):
 recoded = urlencode(base64.encodestring(hexstring.decode('hex')).rstrip())
 print >>sys.stderr, 'recoded:', recoded
 return recoded
def parameters(format):
 if format == 'header':
  formatted = ', '.join(['%s="%s"' % (key, value)
   for key, value in PARAMETERS.items()])
 elif format == 'signing':
  formatted = '&'.join(sorted(['%s=%s' % (key,
   urlencode(value.encode('utf8'))) for
   key, value in (PARAMETERS.items() + SCOPE.items()) if
   key not in ['oauth_signature']]))
 #print >>sys.stderr, format, formatted
 return formatted
def hmac_sha1_test():
 'from tools.ietf.org/html/rfc2202'
 assert sign('\x0b' * 20, 'Hi There') == base64string(
  'b617318655057264e28bc0b6fb378c8ef146be00')
 assert sign('Jefe', 'what do ya want for nothing?') == base64string(
  'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79')
 assert sign('\xaa' * 20, '\xdd' * 50) == base64string(
  '125d7342b9ac11cd91a39af48aa17b4f63f175d3')
 # last test from http://oauth.net/core/1.0/#rfc.section.9.1.1, app. A.5.2
 assert sign('kd94hf93k423kf44&pfkkdhi9sl3r4s00',
  'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26' + \
  'oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D' + \
  'kllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26' + \
  'oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26' + \
  'oauth_version%3D1.0%26size%3Doriginal') == urlencode(
   'tR3+Ty81lMeYAr/Fid0kMTYa/WM=')
 return True
if __name__ == '__main__':
 command = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 print eval(command)(*sys.argv[1:])

Save it as google_oauth.py, and you can link to it like so:

ln -s google_oauth.py hmac_sha1_test.py

to test any of the subroutines. Combined with the use of environment variables, you can compare your results with those of Google's OAuth Playground (other folks here provided the link) and see where you are going wrong. I found many problems with the script that way; there may well be many more. But if you invoke ./google_oauth.py, you should see something like this:

jcomeau@intrepid:~/rentacoder/marchie$ ./google_oauth.py 
signature base string: "'GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dcallback%26oauth_consumer_key%3Danonymous%26oauth_nonce%3Da64720fda018906b%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1302253695%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fcalendar%252Ffeeds%252F'", secret: 'anonymous&'
send: 'GET /accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nAuthorization: OAuth oauth_nonce="a64720fda018906b", oauth_timestamp="1302253695", oauth_consumer_key="anonymous", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="LSJxopFXWN71sTSIBIkNeGgsOjc%3D", oauth_callback="callback"\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: text/plain; charset=UTF-8
header: Date: Fri, 08 Apr 2011 09:08:20 GMT
header: Expires: Fri, 08 Apr 2011 09:08:20 GMT
header: Cache-Control: private, max-age=0
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 1; mode=block
header: Content-Length: 118
header: Server: GSE
header: Connection: close
oauth_token=4%2FfvSIWW9WBHXa_CjInpOf4FdNYhCj&oauth_token_secret=qhB1EGIKjL1pG9POF2ZOcQk3&oauth_callback_confirmed=true

这篇关于oauth 谷歌使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆