Azure Web PubSub 本地隧道工具

Web PubSub 本地隧道为客户提供本地开发环境,以增强其本地开发体验。 无需再使用第三方工具来公开本地端口,使用 Web PubSub 本地隧道作为 Web PubSub 服务和本地服务器之间的隧道,以确保本地开发环境安全、可靠。

通过 Web PubSub 本地隧道,你能够:

  • 将流量通过隧道从 Web PubSub 传输到本地服务器
  • 查看通过隧道从客户端到 Web PubSub 以及到本地服务器的端到端数据流
  • 使用嵌入式上游服务器开始操作
  • 使用简单的客户端开始进行服务器开发

好处:

  • 安全本地:无需向公众公开本地服务器
  • 安全连接:使用 Microsoft Entra ID 和 Web PubSub 访问策略进行连接
  • 简单配置:URL 模板设置为 tunnel:///<your_server_path>
  • 数据检查:清楚地了解数据和工作流

先决条件

  • Node.js 版本 16 或更高版本

安装

npm install -g @azure/web-pubsub-tunnel-tool

使用情况

Usage: awps-tunnel [options] [command]

A local tool to help tunnel Azure Web PubSub traffic to local web app and provide a vivid view to the end to end workflow.

Options:
  -v, --version   Show the version number.
  -h, --help      Show help details.

Commands:
  status          Show the current configuration status.
  bind [options]  Bind configurations to the tool so that you don't need to specify them every time running the tool.
  run [options]   Run the tool.
  help [command]  Display help details for subcommand.

You could also set WebPubSubConnectionString environment variable if you don't want to configure endpoint.

准备凭据

支持连接字符串和 Microsoft Entra ID。

使用连接字符串

  1. 在 Web PubSub 服务门户中,从 Web PubSub 服务门户复制连接字符串。

  2. 将连接字符串设置为本地环境变量并启动 awps-tunnel

export WebPubSubConnectionString="<your connection string>"

使用 Azure 标识

  1. 在 Web PubSub 服务门户中,转到“访问控制”选项卡,并将角色 Web PubSub Service Owner 添加到标识中。

  2. 在本地终端中,使用 Azure CLIaz login 登录到你的标识。

  3. 或者,可以通过定义的环境变量设置帐户信息,或将托管标识身份验证直接用于受支持的 Azure 服务。

运行

  1. 在 Web PubSub 服务门户中,转到“设置”选项卡,指定以 tunnel:/// 开头的事件处理程序 URL 模板,以允许隧道连接。

    在中心设置中设置上游 URL 的屏幕截图。

  2. 使用之前设置的中心运行该工具,例如,使用中心 chat 连接到终结点 https://<awps-host-name>.webpubsub.azure.com

    awps-tunnel run --hub chat --endpoint https://<awps-host-name>.webpubsub.azure.com
    

    也可以使用 awps-tunnel bind --hub chat --endpoint https://<awps-host-name>.webpubsub.azure.com 保存配置,然后使用 awps-tunnel run

  3. 你将看到类似于 Open webview at: http://127.0.0.1:4000 的输出,在浏览器中打开链接,可以看到隧道状态和工作流。

  4. 现在切换到“服务器”选项卡,然后选中“内置 Echo 服务器”启动内置上游服务器,其代码类似于下面所示的示例代码

    启动内置回显服务器的屏幕截图。

  5. 或者,可以在 http://localhost:3000. 启动自己的上游服务器 也可以在使用 awps-tunnel runawps-tunnel bind 时指定选项 --upstream http://localhost:<custom-port>,以便在自定义端口配置自己的上游服务器。 例如,运行以下代码启动此示例上游服务器,当其启动时,上游会将请求发送到 http://localhost:3000/eventhandler/.

    git clone https://github.com/Azure/azure-webpubsub.git
    cd tools/awps-tunnel/server/samples/upstream
    npm install
    npm start
    
  6. 现在切换到“客户端”选项卡,选择 Connect 开始与 Azure Web PubSub 服务建立测试 WebSocket 连接。 你将看到流量通过 Web PubSub 传输到本地隧道,最终到达上游服务器。 隧道选项卡提供请求和响应的详细信息,可让你清楚地了解向上游服务器发出请求的项以及上游服务器对其作出响应的项。

    启动测试 WebSocket 连接并发送消息的屏幕截图。

    显示流量检查的屏幕截图。

揭秘

隧道工具的工作原理是什么? 在后台,工具会启动与 Web PubSub 服务的隧道连接。 隧道连接是连接到 /server/tunnel 终结点的持久连接 (WebSocket),被视为服务器连接的一种。 还可以在服务中使用 ACL 规则来禁用此类连接进行连接。