我有一个appengine应用程序,它需要访问Google Drive上的单个硬编码电子表格。
到目前为止,我已经做到了以下几点:
SpreadsheetService service = new SpreadsheetService("myapp");
service.setUserCredentials("myusername@gmail.com", "myhardcodedpassword");
当我今天用一个新用户尝试时,我得到了InvalidCredentialsException
,尽管用户名和密码肯定是正确的。我在收件箱里收到一封电子邮件,说已经阻止了可疑的登录,似乎没有办法再次启用它们。
我也知道在源代码中硬编码密码是不好的做法。
然而,我已经在网上广泛阅读了如何启用OAuth/OAuth2来实现这一点,最终浪费了几个小时来拼凑博客、stackoverflow答案等信息片段,但都无济于事。
理想情况下,解决方案将涉及生成长期访问令牌的初始过程,然后可以将其硬编码到应用程序中。
我想要一个如何实现这一目标的明确步骤列表?
发布于 2014-04-04 14:15:52
编辑:由于谷歌重新设计了应用程序接口控制台,下面步骤的细节已经改变-请参阅评论
好的,一步一步来
OAuth
tokens‘
刷新令牌相当于您的长寿用户名/密码,因此这是您要硬编码的内容(或者将其存储在您的应用程序可以检索到的安全位置)。
当您需要访问Google电子表格时,您可以调用
POST https://accounts.google.com/o/oauth2/token
content-type: application/x-www-form-urlencoded
client_secret=************&grant_type=refresh_token&refresh_token=1%2xxxxxxxxxx&client_id=999999999999.apps.googleusercontent.com
它将为您返回一个访问令牌
{
"access_token": "ya29.yyyyyyyyyyyyyyyyyy",
"token_type": "Bearer",
"expires_in": 3600
}
无论何时访问spreadsheet API,都要将访问令牌放入http标头。
Authorization: Bearer ya29.yyyyyyyyyyyyyyyyy
你就完事了
发布于 2014-04-30 12:50:18
Pinoyyid确实提供了极好的帮助。我想继续使用Python代码,它将允许访问个人(可通过web访问) Google Drive。
这在Google App Engine中运行良好(作为web应用程序的一部分),也可以在桌面上独立运行(假设Google App Engine SDK安装在您的机器available from: [https://developers.google.com/appengine/downloads]上)。
在我的例子中,我在Pinyyid的过程中添加了https://www.googleapis.com/auth/drive作用域,因为我想访问我所有的Google Drive文件。
按照Pinoyyid的指示获取刷新令牌等之后,这个小Python脚本将获得Google驱动器上所有文件的列表:
import httplib2
import datetime
from oauth2client.client import OAuth2Credentials
from apiclient.discovery import build
API_KEY = 'AIz...' # from "Key for Server Applications" from "Public API Access" section of Google Developers Console
access_token = "ya29..." # from Piinoyyid's instructions
refresh_token = "1/V..." # from Piinoyyid's instructions
client_id = '654....apps.googleusercontent.com' # from "Client ID for web application" from "OAuth" section of Google Developers Console
client_secret = '6Cl...' # from "Client ID for web application" from "OAuth" section of Google Developers Console
token_expiry = datetime.datetime.utcnow() - datetime.timedelta(days=1)
token_uri = 'https://accounts.google.com/o/oauth2/token'
user_agent = 'python urllib (I reckon)'
def main():
service = createDrive()
dirlist = service.files().list(maxResults=30)
print 'dirlist', dirlist
result = dirlist.execute()
print 'result', result
def createDrive():
credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http, developerKey=API_KEY)
main()
我非常感谢在解决这个问题的过程中提供步骤的所有人。
https://stackoverflow.com/questions/22863104
复制相似问题