2016-11-16 75 views
4

我正在編寫使用Google身份驗證登錄的腳本。我目前正在獲取訪問令牌和用戶的電子郵件地址,並將其傳遞給我使用imap連接到gmail的函數,然後使用電子郵件執行一些操作。我生成了身份驗證字符串,就像我見過別人做網上但是我收到此錯誤:使用oauth令牌連接到使用imap的Gmail時身份驗證失敗

Traceback (most recent call last): 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 2000, in __call__ 
    return self.wsgi_app(environ, start_response) 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1991, in wsgi_app 
    response = self.make_response(self.handle_exception(e)) 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1567, in handle_exception 
    reraise(exc_type, exc_value, tb) 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1988, in wsgi_app 
    response = self.full_dispatch_request() 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request 
    rv = self.handle_user_exception(e) 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1544, in handle_user_exception 
    reraise(exc_type, exc_value, tb) 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request 
    rv = self.dispatch_request() 
    File "/Library/Python/2.7/site-packages/flask/app.py", line 1625, in dispatch_request 
    return self.view_functions[rule.endpoint](**req.view_args) 
    File "/Users/Harrison/Desktop/Uber/UberStats.py", line 60, in index 
    return Uber_Cost(email_address, access_token) 
    File "/Users/Harrison/Desktop/Uber/UberStats.py", line 103, in Uber_Cost 
    mail.authenticate('XOAUTH2', lambda x: auth_string) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/imaplib.py", line 364, in authenticate 
    raise self.error(dat[-1]) 
error: [AUTHENTICATIONFAILED] Invalid credentials (Failure) 

我打印出的訪問代碼,以及爲我與登錄的電子郵件地址,所以我知道這些值不爲空。我是否生成auth字符串錯誤?我沒有正確驗證imap嗎?

這裏是我的代碼:

from flask import Flask, request, url_for, session, redirect, jsonify 
from flask_oauth import OAuth 
import json 
import imaplib 
import email 
from bs4 import BeautifulSoup 
import base64 





GOOGLE_CLIENT_ID = '****' 
GOOGLE_CLIENT_SECRET = '***' 
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console 

SECRET_KEY = 'Uber' 
DEBUG = True 

app = Flask(__name__) 
app.secret_key = 'Uber' 
oauth = OAuth() 

google = oauth.remote_app('google', 
          base_url='https://www.google.com/accounts/', 
          authorize_url='https://accounts.google.com/o/oauth2/auth', 
          request_token_url=None, 
          request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email', 
               'response_type': 'code'}, 
          access_token_url='https://accounts.google.com/o/oauth2/token', 
          access_token_method='POST', 
          access_token_params={'grant_type': 'authorization_code'}, 
          consumer_key=GOOGLE_CLIENT_ID, 
          consumer_secret=GOOGLE_CLIENT_SECRET) 


@app.route('/') 
def index(): 
    access_token = session.get('access_token') 
    if access_token is None: 
     return redirect(url_for('login')) 

    access_token = access_token[0] 
    from urllib2 import Request, urlopen, URLError 

    headers = {'Authorization': 'OAuth '+access_token} 
    req = Request('https://www.googleapis.com/oauth2/v1/userinfo', 
        None, headers) 
    try: 
     res = urlopen(req) 
    except URLError, e: 
     if e.code == 401: 
      # Unauthorized - bad token 
      session.pop('access_token', None) 
      return redirect(url_for('login')) 
     return res.read() 
    j = json.loads(res.read()) 
    email_address = j['email'] 
    print email_address, access_token 
    return Uber_Cost(email_address, access_token) 


@app.route('/login') 
def login(): 
    callback=url_for('authorized', _external=True) 
    return google.authorize(callback=callback) 



@app.route(REDIRECT_URI) 
@google.authorized_handler 
def authorized(resp): 
    access_token = resp['access_token'] 
    session['access_token'] = access_token, '' 
    return redirect(url_for('index')) 


@google.tokengetter 
def get_access_token(): 
    return session.get('access_token') 


def GenerateOAuth2String(username, access_token, base64_encode=True): 
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) 
    if base64_encode: 
     auth_string = base64.b64encode(auth_string) 
    return auth_string 




def Uber_Cost(email_address, access_token): 


    auth_string = GenerateOAuth2String(email_address, access_token, base64_encode=False) 



    mail = imaplib.IMAP4_SSL('imap.gmail.com') 
    mail.debug = 4 
    mail.authenticate('XOAUTH2', lambda x: auth_string) 
    mail.select('INBOX') 
+0

你應該看看這個答案:http://stackoverflow.com/a/5366380/7090605 –

+0

@JakeConway這是oauth2。我不認爲oauth 1擁有用戶祕密令牌。我怎麼得到這個? – Harrison

+0

它看起來像你有Oauth2令牌。你需要一個access_token來連接。 – Max

回答

0

它看起來就像你根據你最新的代碼獲得了身份驗證()方法了。

您還需要使用https://mail.google.com/ OAuth範圍才能對IMAP和SMTP服務器進行身份驗證。

也就是說它添加到你的範圍要求,並確保您的應用程序配置爲在谷歌應用程序控制臺此範圍:

request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email https://mail.google.com/', 
              'response_type': 'code'}, 

的谷歌的OAuth2協議和範圍在其developer page被記錄在案。

+0

代碼更新爲我目前擁有的。那去哪裏?在請求令牌參數中? – Harrison

+0

是的,我相信示波器是空間分離的。我不確定,但您可能還需要轉到您的應用程序控制臺並將其添加到您的項目中。 – Max

+0

順便說一句,如果您更改範圍,您可能需要刷新您擁有的任何當前令牌。 – Max

相關問題