Skip to content

Cordova - 白名单

Cordova - 白名单 (网络请求与导航控制)

Section titled “Cordova - 白名单 (网络请求与导航控制)”

cordova-plugin-whitelist 插件提供了一种机制,用于控制你的应用程序被允许发出哪些网络请求(例如图片、XHR 请求等),以及应用程序或外部应用可以打开哪些 URL。当你创建一个新的 Cordova 项目时,此插件通常会默认安装。它的配置主要通过 config.xml 文件以及 index.html 中的内容安全策略 (Content Security Policy, CSP) meta 标签进行管理。

安全至关重要。白名单有助于防止你的应用程序访问恶意网站或将数据泄露到意想不到的目的地。

config.xml 文件中的 <allow-navigation> 标签控制 WebView 本身可以导航到哪些 URL。如果某个 URL 与任何 <allow-navigation> 标签都不匹配,则导航尝试将被阻止。默认情况下,允许导航到 file:// URL(你的本地应用文件)。

示例:允许导航到 https://example.com 及其子域:

<!-- In config.xml -->
<allow-navigation href="https://example.com/*" />
<allow-navigation href="https://*.anotherexample.net/*" />

星号 * 用作通配符 (wildcard)。https://example.com/* 允许使用 HTTPS 协议导航到 example.com 上的任何页面。要允许所有子域 (subdomains),可以使用 *://*.example.com/*(尽管指定协议如 https* 通常比 * 更安全)。

config.xml 文件中的 <allow-intent> 标签控制应用程序被允许请求操作系统打开哪些 URL。例如,在拨号应用中打开 tel: 链接或在系统浏览器中打开 http: 链接。Cordova 默认的 config.xml 通常包含常见的协议 (scheme) 的意图,如 http、https、tel、sms、mailto 和 geo。

示例:允许在系统浏览器中打开 HTTP 和 HTTPS 链接:

<!-- In config.xml -->
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

<access> 标签(来自 Cordova 核心,对于较旧的 Android 版本常与白名单插件一起使用,但在现代 Android 和 iOS 上 CSP 是主要的机制)控制应用程序的 WebView 可以发出哪些网络请求(例如 XHR、图片)。一个常见的默认设置是 <access origin="*" />,它允许请求任何域。为了增强安全性,你应该将其限制为应用程序需要通信的特定域。

示例:仅允许对 https://api.myapp.com 发出网络请求:

<!-- In config.xml -->
<access origin="https://api.myapp.com" />
<!-- To allow subdomains: -->
<!-- <access origin="https://*.myapp.com" /> -->

注意:对于较新的 Cordova 版本(尤其是在使用 cordova-android@7+ 的 Android 上),CSP 是控制 WebView 中网络请求的主要机制。<access origin> 可能仍然会影响插件行为或较旧的平台。

内容安全策略 (Content Security Policy, CSP) 是一个重要的安全层,有助于检测和缓解某些类型的攻击,如跨站脚本攻击 (Cross-Site Scripting, XSS) 和数据注入。它通过在 index.html 文件中使用 <meta> 标签来定义。

一个现代 Cordova 应用的默认 CSP 可能如下所示:

<!-- In index.html -->
<head>
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' data: cdvfile: file: gap: https://ssl.gstatic.com;
style-src 'self' 'unsafe-inline';
script-src 'self' 'unsafe-eval';
media-src *;
img-src 'self' data: cdvfile: file: content:;">
<!-- Adjust 'unsafe-inline' and 'unsafe-eval' as much as possible for better security -->
</head>

常见指令说明:

示例:一个更严格的 CSP,仅允许从自身和特定的 API 域加载资源:

<!-- In index.html -->
<head>
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' https://api.example.com;
connect-src 'self' https://api.example.com wss://socket.example.com;
style-src 'self' 'unsafe-inline';
script-src 'self';
img-src 'self' data:;">
</head>

最佳实践是将 CSP 设置得尽可能严格。从一个严格的策略开始,然后根据应用程序的具体需求逐步放宽权限。对于初学者来说,Cordova 提供的默认 CSP 是一个不错的起点。随着你越来越熟悉,可以根据应用需求收紧它。

更多详情,请参阅官方的 cordova-plugin-whitelist 文档和 MDN Web Docs 关于内容安全策略的内容。