You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySide6 QtWebEngine嵌入浏览器谷歌登录被拒:如何实现谷歌账号认证

Qt WebEngine嵌入应用谷歌登录被拦截的解决方法

问题原因

谷歌登录的安全机制会检测浏览器环境的多重特征(不止User-Agent字符串),即使你移除了UA中的Qt标识,Qt WebEngine底层的Chromium实例仍会被识别为非官方嵌入式浏览器,触发安全拦截,提示“此浏览器或应用可能不安全”。

解决方案1:调整WebEngine模拟Chrome环境

通过添加命令行参数,让Qt WebEngine更贴近标准Chrome的运行特征,绕过部分检测:

修改你的代码如下:

import sys
from PySide6.QtCore import QUrl, QCoreApplication, Qt
from PySide6.QtWidgets import QApplication
from PySide6.QtWebEngineCore import QWebEngineProfile, QWebEnginePage
from PySide6.QtWebEngineWidgets import QWebEngineView

# 添加命令行参数,模拟Chrome的版本与品牌特征
sys.argv.extend([
    "--force-major-version-to=140",  # 强制版本号匹配Chrome 140
    "--enable-features=UseChromeOSBrand",  # 启用Chrome品牌标识
    "--disable-features=BrowserControls",  # 禁用Qt特有的控件特征
])

QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_EnableHighDpiScaling)

SIGN_IN_WITH_GOOGLE = (
    "https://accounts.google.com/o/oauth2/v2/auth"
    "?client_id=407408718192.apps.googleusercontent.com"
    "&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground"
    "&response_type=code&scope=email"
)

def main():
    app = QApplication(sys.argv)
    profile = QWebEngineProfile("mre-profile", app)
    
    # 直接使用标准Chrome的UA字符串
    ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
    profile.setHttpUserAgent(ua)

    view = QWebEngineView()
    view.setPage(QWebEnginePage(profile, view))
    view.setUrl(QUrl(SIGN_IN_WITH_GOOGLE))
    view.resize(1000, 820)
    view.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

⚠️ 注意:这种方法依赖谷歌检测机制的漏洞,可能随时失效。

解决方案2:使用谷歌官方桌面OAuth流程(推荐)

谷歌官方为桌面应用提供了专门的OAuth授权流程,通过系统默认浏览器打开登录页面,完全符合安全规范,不会被拦截:

步骤说明

  1. 前往谷歌云平台,创建桌面应用类型的OAuth客户端ID
  2. 使用requests-oauthlib库实现授权流程(需先安装:pip install requests-oauthlib)

代码示例:

import sys
from PySide6.QtWidgets import QApplication, QMessageBox, QInputDialog
from requests_oauthlib import OAuth2Session

# 替换为你自己的桌面客户端ID
CLIENT_ID = "your-desktop-client-id.apps.googleusercontent.com"
REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"  # 桌面应用专用回调地址
SCOPE = ["email"]

def main():
    app = QApplication(sys.argv)
    
    # 初始化OAuth会话
    oauth = OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
    authorization_url, _ = oauth.authorization_url(
        "https://accounts.google.com/o/oauth2/v2/auth",
        access_type="offline",
        prompt="select_account"
    )
    
    # 调用系统默认浏览器打开授权页面
    import webbrowser
    webbrowser.open(authorization_url)
    
    # 弹窗让用户输入浏览器中显示的授权码
    code, ok = QInputDialog.getText(None, "输入授权码", "请复制浏览器中的授权码并粘贴:")
    if not ok:
        sys.exit(1)
    
    # 获取访问令牌
    try:
        token = oauth.fetch_token(
            "https://oauth2.googleapis.com/token",
            code=code.strip(),
            client_id=CLIENT_ID,
            include_client_id=True
        )
        
        # 用令牌获取用户邮箱信息
        response = oauth.get("https://www.googleapis.com/oauth2/v1/userinfo")
        if response.ok:
            user_info = response.json()
            QMessageBox.information(None, "登录成功", f"欢迎,{user_info['email']}")
        else:
            QMessageBox.critical(None, "登录失败", "无法获取用户信息")
    except Exception as e:
        QMessageBox.critical(None, "错误", f"授权失败:{str(e)}")
    
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

这种方法是谷歌官方认可的桌面应用授权方式,长期稳定可靠。

内容的提问来源于stack exchange,提问作者Franck Dernoncourt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.09 01:14:52