使用PyQt4 / 5隐式OAuth2授权

时间:2016-02-13 22:22:21

标签: python oauth-2.0 pyqt python-requests qwebview

我一直在研究一个使用OAuth2识别用户的python应用程序。我似乎已经成功实现了OAuth2隐式授权的工作流程(通常用于已安装和用户代理的应用程序),但在接收令牌的最后一步,似乎出现了问题。

每当用户需要进行身份验证时,就会生成一个显示登录页面的PyQt QWebView窗口(基于webkit)。用户登录并允许我的应用程序的作用域权限后,OAuth2服务器将重定向到预先指定的redirect_uri。

问题在于,当使用QWebView浏览器时,通常出现在#之后的令牌字符串似乎已从URL中删除:QWebView返回的URL只是基本的redirect_uri。

如果我复制粘贴OAuth授权网址并按照常规网络浏览器(如Chrome或Firefox)登录和授权的相同步骤,我会看到redirect_uri包含令牌字符串,所以问题不会在OAuth2进程中,但在我这边的实现中必须出错。

这种行为是否是QWebView或webkit实现所固有的?我错误地读出了QUrl?

为了完整性,这是我的代码:

osf.py模块,为Open Science Framework生成OAuth2 URL。

# Import basics
import sys
import os

# Module for easy OAuth2 usage, based on the requests library,
# which is the easiest way to perform HTTP requests.

# OAuth2Session object
from requests_oauthlib import OAuth2Session
# Mobile application client that does not need a client_secret
from oauthlib.oauth2 import MobileApplicationClient

#%%----------- Main configuration settings ----------------
client_id = "cbc4c47b711a4feab974223b255c81c1"
# TESTED, just redirecting to Google works in normal browsers
# the token string appears in the url of the address bar
redirect_uri = "https://google.nl"

# Generate correct URLs
base_url = "https://test-accounts.osf.io/oauth2/"
auth_url = base_url + "authorize"
token_url = base_url + "token"
#%%--------------------------------------------------------

mobile_app_client = MobileApplicationClient(client_id)

# Create an OAuth2 session for the OSF
osf_auth = OAuth2Session(
    client_id, 
    mobile_app_client,
    scope="osf.full_write", 
    redirect_uri=redirect_uri,
)

def get_authorization_url():
    """ Generate the URL with which one can authenticate at the OSF and allow 
    OpenSesame access to his or her account."""
    return osf_auth.authorization_url(auth_url)

def parse_token_from_url(url):
    token = osf_auth.token_from_fragment(url)
    if token:
        return token
    else:
        return osf_auth.fetch_token(url)

主程序,打开一个带登录界面的QWebView浏览器窗口

# Oauth2 connection to OSF
import off
import sys
from PyQt4 import QtGui, QtCore, QtWebKit

class LoginWindow(QtWebKit.QWebView):
    """ A Login window for the OSF """

    def __init__(self):
        super(LoginWindow, self).__init__()
        self.state = None
        self.urlChanged.connect(self.check_URL)

    def set_state(self,state):
        self.state = state

    def check_URL(self, url):
        #url is a QUrl object, covert it to string for easier usage
        url_string = url.toEncoded()
        print(url_string)

        if url.hasFragment():
            print("URL CHANGED: On token page: {}".format(url))
            self.token = osf.parse_token_from_url(url_string)
            print(self.token)
        elif not osf.base_url in url_string:
            print("URL CHANGED: Unexpected url")

if __name__ == "__main__":
    """ Test if user can connect to OSF. Opens up a browser window in the form
    of a QWebView window to do so."""
    # Import QT libraries

    app = QtGui.QApplication(sys.argv)
    browser = LoginWindow()

    auth_url, state = osf.get_authorization_url()
    print("Generated authorization url: {}".format(auth_url))

    browser_url = QtCore.QUrl.fromEncoded(auth_url)
    browser.load(browser_url)
    browser.set_state(state)
    browser.show()

    exitcode = app.exec_()
    print("App exiting with code {}".format(exitcode))
    sys.exit(exitcode)

基本上,QWebView的url_changed事件提供给check_URL函数的url在从OAuth服务器返回时从不包含OAuth令牌片段,无论我用于redirect_uri(在本例中我只是重定向到谷歌为了简单起见)。

有人可以帮我这个吗?我已经用尽了在哪里寻找解决这个问题的方法。

1 个答案:

答案 0 :(得分:2)

这似乎是Webkit / Safari中的已知错误:

https://bugs.webkit.org/show_bug.cgi?id=24175 https://phabricator.wikimedia.org/T110976#1594914

基本上它没有修复,因为根据HTTP规范,人们不同意所需的行为。 How do I preserve uri fragment in safari upon redirect?描述了一种可能的解决方法,但我无法对此进行测试。

修改

我设法找到一个(不那么优雅)解决这个问题的工作。我没有使用QWebView中的urlChanged事件(它没有显示OAuth服务器完成的301重定向),而是使用了QNetworkAccessManager的finished()事件。在任何 http请求完成后,这会被触发(因此对于页面的所有链接内容,例如图像,样式表等等,所以你必须进行大量的过滤)。

所以现在我的代码看起来像这样:

class LoginWindow(QtWebKit.QWebView):
    """ A Login window for the OSF """
    # Login event is emitted after successfull login
    logged_in = QtCore.pyqtSignal(['QString'])  

    def __init__(self):
        super(LoginWindow, self).__init__()

        # Create Network Access Manager to listen to all outgoing
        # HTTP requests. Necessary to work around the WebKit 'bug' which
        # causes it drop url fragments, and thus the access_token that the
        # OSF Oauth system returns
        self.nam = self.page().networkAccessManager()

        # Connect event that is fired if a HTTP request is completed.
        self.nam.finished.connect(self.checkResponse)

    def checkResponse(self,reply):
        request = reply.request()
        # Get the HTTP statuscode for this response
        statuscode = reply.attribute(request.HttpStatusCodeAttribute)
        # The accesstoken is given with a 302 statuscode to redirect

        if statuscode == 302:
            redirectUrl = reply.attribute(request.RedirectionTargetAttribute)
            if redirectUrl.hasFragment():
                r_url = redirectUrl.toString()
                if osf.redirect_uri in r_url:
                    print("Token URL: {}".format(r_url))
                    self.token = osf.parse_token_from_url(r_url)
                    if self.token:
                        self.logged_in.emit("login")
                        self.close()