gmail api禁止使用访问令牌的错误

时间:2014-07-25 22:52:48

标签: python django gmail

我正在尝试使用gmail api从中获取数据。以下是程序问题。首先,我向谷歌服务器提交请求,以便用户可以为我的应用程序指定权限:

def oauth_connect(request):
    if request.method == 'GET' and request.user.is_authenticated():
        auth_uri = 'https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/gmail.compose&client_id={0}&redirect_uri={1}&approval_prompt=force'.format(GOOGLE_CLIENT_ID, HOSTNAME_URI + 'oauth2callback')
        return HttpResponseRedirect(auth_uri)

在回调中,我坚持谷歌发送的访问令牌。我也期待刷新令牌在响应中,但显然它不存在。

def google_oauth_return(request):
    if request.method == 'GET' and request.user.is_authenticated():
        # Get the auth code from the GET request
        code = request.GET['code']
        agent = Agent.objects.get(user=request.user)

        # Create a list of 2-tuples for the parameters to send in the POST request back to eventbrite to get the auth token
        post_data = [('code', code), ('client_secret', GOOGLE_CLIENT_SECRET), ('client_id', GOOGLE_CLIENT_ID), 
            ('redirect_uri', HOSTNAME_URI + 'oauth2callback'), ('grant_type', 'authorization_code'),
        ]

        # Send POST request and get json sent back
        result = urllib2.urlopen('https://accounts.google.com/o/oauth2/token', urllib.urlencode(post_data))
        pprint.pprint(result)
        # Load the json into a python dict
        data = json.load(result)
        pprint.pprint(data)
        # Get the access token
        access_token = data['access_token']
        expiration_time = data['expires_in']
        if 'refresh_token' in data:
            refresh_token = data['refresh_token']
        else:
            refresh_token = ''
        agent.google_access_token = access_token
        agent.google_access_token_expiration_time = datetime.utcnow().replace(tzinfo=tz.tzutc()) + timedelta(seconds=int(expiration_time))
        agent.google_refresh_token = refresh_token
        agent.save()

        return HttpResponseRedirect('/profile')

但是,当我使用访问令牌来提取数据时,我发出了http 403 forbidden error。

def get_gmail_data(request):
    if request.method == 'GET':
        agent = Agent.objects.get(user=request.user)
        access_token = agent.google_access_token
        pprint.pprint(access_token)
        expiration_time = agent.google_access_token_expiration_time
        # TODO Check if access token expired. tzinfo=tz.utc is used because utcnow returns a offset-naive datetime
        # Set up HTTPS request and add access token as a header
        get_mail = urllib2.Request('https://www.googleapis.com/gmail/v1/users/me/messages')
        get_mail.add_header('Authorization', 'Bearer ' + access_token)
        # Open the connection and get the json, turn it into a python dict
        gmail_data = urllib2.urlopen(get_mail)
        gmail = json.load(gmail_data)

        pprint.pprint(gmail)

我是oauth的新手,所以如果有人能指出这个问题会有所帮助。

1 个答案:

答案 0 :(得分:1)

根据Google APIs Explorer,你正在使用的OAtuth 2.0范围:

https://www.googleapis.com/auth/gmail.compose

...只允许:

  

管理草稿和发送电子邮件

但你正试图将它用于此:

https://www.googleapis.com/gmail/v1/users/me/messages

即查看电子邮件。你需要合适的范围:

https://mail.google.com/

...允许:

  

查看和管理您的邮件

因此错误消息是完全合适的。您已经要求并获得了做一件事的许可,尝试做了一些不同的事情,并且获得了权限错误。