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

Ubuntu22下Beeware Toga WebView加载证书链断裂URL失败求助

问题:Toga WebView加载证书链断裂的URL时出现“Unacceptable TLS certificate”错误

我正在开发一个仅支持打开指定URL(https://14.139.222.78:443)的简单WebView类型应用,但加载mainbox时显示“Unacceptable TLS certificate”错误。以下是{APPNAME}/src/{APPNAME}/app.py的最小可复现代码:

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW


class APPMAIL(toga.App):

    def startup(self):
        main_box = toga.Box(style=Pack(flex=1, direction="column"))
        webview = toga.WebView(user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")

        webview.url = "https://14.139.222.78:443"

        main_box.add(webview)        
        
        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = main_box
        self.main_window.show()

def main():
    return APPMAIL()

该URL在浏览器中可正常打开,但Beeware应用的WebView无法加载,我希望在应用中显示与浏览器一致的内容。经分析,Ubuntu22系统下Toga WebView的证书链无法验证到根证书,而浏览器可通过额外信息验证此类断裂的证书链。请问是否可以在Ubuntu22的Toga WebView中打开这类证书链断裂的URL?如果可以,该如何操作?


解决方案

可以在Ubuntu22的Toga WebView中加载这类证书链断裂的URL,有两种可行方案:

方案1:临时忽略TLS证书错误(仅用于测试场景)

Toga在Linux平台下基于WebKitGTK实现WebView,我们可以直接调用WebKitGTK的API跳过证书验证:

  1. 导入WebKitGTK的相关依赖
  2. 获取WebView的原生控件,设置忽略TLS错误策略或自定义验证逻辑

修改后的完整代码如下:

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
import gi
gi.require_version('WebKit2', '4.0')
from gi.repository import WebKit2


class APPMAIL(toga.App):

    def startup(self):
        main_box = toga.Box(style=Pack(flex=1, direction="column"))
        webview = toga.WebView(user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")

        # 获取Linux平台下的原生WebKitWebView控件
        native_webview = webview._impl.native
        # 设置忽略TLS证书错误,允许继续加载
        native_webview.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE)

        webview.url = "https://14.139.222.78:443"

        main_box.add(webview)        
        
        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = main_box
        self.main_window.show()

def main():
    return APPMAIL()

如果需要更精细的控制(比如仅信任特定证书),可以通过监听load-failed-with-tls-errors信号自定义验证逻辑:

# 在startup方法中替换set_tls_errors_policy的代码
def on_tls_error(webview, load_event, certificate, errors):
    # 这里可以添加证书检查逻辑,比如比对证书指纹
    # 返回True表示忽略错误,继续加载
    return True

native_webview.connect("load-failed-with-tls-errors", on_tls_error)

方案2:添加缺失的根证书到系统信任存储(生产环境推荐)

忽略证书错误存在安全风险,生产环境建议手动补全证书链:

  1. 在浏览器中打开目标URL,导出网站的根证书(格式为PEM)
  2. 将证书文件复制到Ubuntu系统的/usr/local/share/ca-certificates/目录
  3. 执行命令更新系统证书存储:
    sudo update-ca-certificates
    

完成后,Toga的WebView会自动信任该证书,无需修改代码即可正常加载页面。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:05:20