您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Azure Functions 进行 Azure SignalR 服务身份验证Tutorial: Azure SignalR Service authentication with Azure Functions

本教程逐步讲解如何使用 Azure Functions、应用服务身份验证和 SignalR 服务生成一个支持身份验证和私密消息传送的聊天室。A step by step tutorial to build a chat room with authentication and private messaging using Azure Functions, App Service Authentication, and SignalR Service.

介绍Introduction

使用的技术Technologies used

先决条件Prerequisites

本教程需要以下软件。The following software is required to build this tutorial.

登录到 Azure 门户Sign into the Azure portal

转到 Azure 门户并使用自己的凭据登录。Go to the Azure portal and sign in with your credentials.

创建 Azure SignalR 服务实例Create an Azure SignalR Service instance

将在本地生成并测试 Azure Functions 应用。You will build and test the Azure Functions app locally. 该应用将访问 Azure 中需要提前创建的 SignalR 服务实例。The app will access a SignalR Service instance in Azure that needs to be created ahead of time.

  1. 单击用于创建新 Azure 资源的“创建资源”( + ) 按钮。 Click on the Create a resource (+) button for creating a new Azure resource.

  2. 搜索“SignalR 服务”并将其选中。 Search for SignalR Service and select it. 单击“创建”。 Click Create.

    新建 SignalR 服务

  3. 输入以下信息。Enter the following information.

    NameName Value
    资源名称Resource name SignalR 服务实例的唯一名称A unique name for the SignalR Service instance
    Resource groupResource group 创建具有唯一名称的新资源组Create a new resource group with a unique name
    位置Location 选择靠近自己的位置Select a location close to you
    定价层Pricing Tier 免费Free
  4. 单击“创建”。 Click Create.

  5. 部署该实例后,在门户中打开它并找到其“设置”页。After the instance is deployed, open it in the portal and locate its Settings page. 将服务模式设置更改为“无服务器” 。Change the Service Mode setting to Serverless.

    SignalR 服务模式

初始化函数应用Initialize the function app

创建新的 Azure Functions 项目Create a new Azure Functions project

  1. 在新的 VS Code 窗口,使用菜单中的 File > Open Folder 在适当的位置创建一个空文件夹并将其打开。In a new VS Code window, use File > Open Folder in the menu to create and open an empty folder in an appropriate location. 这是要生成的应用程序的主项目文件夹。This will be the main project folder for the application that you will build.

  2. 使用 VS Code 中的 Azure Functions 扩展初始化主项目文件夹中的函数应用。Using the Azure Functions extension in VS Code, initialize a Function app in the main project folder.

    1. 在 VS Code 的菜单中选择“视图”>“命令面板”(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)打开命令面板。 Open the Command Palette in VS Code by selecting View > Command Palette from the menu (shortcut Ctrl-Shift-P, macOS: Cmd-Shift-P).

    2. 搜索“Azure Functions: Create New Project”命令并将其选中。Search for the Azure Functions: Create New Project command and select it.

    3. 此时应会显示主项目文件夹。The main project folder should appear. 选择该文件夹(或使用“浏览”找到它)。Select it (or use "Browse" to locate it).

    4. 当系统提示选择语言时,请选择“JavaScript”。 In the prompt to choose a language, select JavaScript.

      创建函数应用

安装函数应用扩展Install function app extensions

本教程使用 Azure Functions 绑定来与 Azure SignalR 服务交互。This tutorial uses Azure Functions bindings to interact with Azure SignalR Service. 与其他大多数绑定一样,SignalR 服务绑定可用作扩展,需要先通过 Azure Functions Core Tools CLI 安装该扩展才能使用它。Like most other bindings, the SignalR Service bindings are available as an extension that needs to be installed using the Azure Functions Core Tools CLI before they can be used.

  1. 在 VS Code 的菜单中选择“视图”>“终端”(Ctrl-`) 打开一个终端。 Open a terminal in VS Code by selecting View > Terminal from the menu (Ctrl-`).

  2. 确保当前目录是主项目文件夹。Ensure the main project folder is the current directory.

  3. 安装 SignalR 服务函数应用扩展。Install the SignalR Service function app extension.

    func extensions install -p Microsoft.Azure.WebJobs.Extensions.SignalRService -v 1.0.0
    

配置应用程序设置Configure application settings

在本地运行和调试 Azure Functions 运行时时,将从 local.settings.json 读取应用程序设置。When running and debugging the Azure Functions runtime locally, application settings are read from local.settings.json. 使用前面创建的 SignalR 服务实例的连接字符串更新此文件。Update this file with the connection string of the SignalR Service instance that you created earlier.

  1. 在 VS Code 的“资源管理器”窗格中选择“local.settings.json”并将其打开。 In VS Code, select local.settings.json in the Explorer pane to open it.

  2. 将该文件的内容替换为以下内容。Replace the file's contents with the following.

    {
        "IsEncrypted": false,
        "Values": {
            "AzureSignalRConnectionString": "<signalr-connection-string>",
            "WEBSITE_NODE_DEFAULT_VERSION": "10.14.1",
            "FUNCTIONS_WORKER_RUNTIME": "node"
        },
        "Host": {
            "LocalHttpPort": 7071,
            "CORS": "http://127.0.0.1:5500",
            "CORSCredentials": true
        }
    }
    
    • 在名为 AzureSignalRConnectionString 的设置中输入 Azure SignalR 服务连接字符串。Enter the Azure SignalR Service connection string into a setting named AzureSignalRConnectionString. 在 Azure 门户中,从 Azure SignalR 服务资源的“密钥”页中获取该值;可以使用主连接字符串或辅助连接字符串。 Obtain the value from the Keys page in the Azure SignalR Service resource in the Azure portal; either the primary or secondary connection string can be used.

    • 不会在本地使用 WEBSITE_NODE_DEFAULT_VERSION 设置,但部署到 Azure 时需要此设置。The WEBSITE_NODE_DEFAULT_VERSION setting is not used locally, but is required when deployed to Azure.

    • Host 节配置本地 Functions 主机的端口和 CORS 设置(在 Azure 中运行时,此设置不起作用)。The Host section configures the port and CORS settings for the local Functions host (this setting has no effect when running in Azure).

      备注

      实时服务器通常配置为从 http://127.0.0.1:5500 提供内容。Live Server is typically configured to serve content from http://127.0.0.1:5500. 如果你发现它使用不同的 URL,或者你使用不同的 HTTP 服务器,请更改 CORS 设置以反映正确来源。If you find that it is using a different URL or you are using a different HTTP server, change the CORS setting to reflect the correct origin.

      获取 SignalR 服务密钥

  3. 保存文件。Save the file.

创建一个用于在 SignalR 服务中验证用户身份的函数Create a function to authenticate users to SignalR Service

当聊天应用在浏览器中首次打开时,需要使用有效的连接凭据连接到 Azure SignalR 服务。When the chat app first opens in the browser, it requires valid connection credentials to connect to Azure SignalR Service. 我们将在函数应用中创建名为 negotiate 的 HTTP 触发的函数,以返回此连接信息。You'll create an HTTP triggered function named negotiate in your function app to return this connection information.

备注

此函数必须命名为 negotiate ,因为 SignalR 客户端需要以 /negotiate 结束的终结点。This function must be named negotiate as the SignalR client requires an endpoint that ends in /negotiate.

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure Functions: Create Function”命令。Search for and select the Azure Functions: Create Function command.

  3. 出现提示时,请提供以下信息。When prompted, provide the following information.

    NameName Value
    函数应用文件夹Function app folder 选择主项目文件夹Select the main project folder
    模板Template HTTP 触发器HTTP Trigger
    NameName negotiatenegotiate
    授权级别Authorization level 匿名Anonymous

    将创建包含新函数的名为 negotiate 的文件夹。A folder named negotiate is created that contains the new function.

  4. 打开 negotiate/function.json 以配置函数的绑定。Open negotiate/function.json to configure bindings for the function. 按如下所示修改该文件的内容。Modify the content of the file to the following. 这会添加一个用于生成有效凭据的输入绑定,使客户端能够连接到名为 chat 的 Azure SignalR 服务中心。This adds an input binding that generates valid credentials for a client to connect to an Azure SignalR Service hub named chat.

    {
        "disabled": false,
        "bindings": [
            {
                "authLevel": "anonymous",
                "type": "httpTrigger",
                "direction": "in",
                "name": "req"
            },
            {
                "type": "http",
                "direction": "out",
                "name": "res"
            },
            {
                "type": "signalRConnectionInfo",
                "name": "connectionInfo",
                "userId": "",
                "hubName": "chat",
                "direction": "in"
            }
        ]
    }
    

    signalRConnectionInfo 绑定中的 userId 属性用于创建已经过身份验证的 SignalR 服务连接。The userId property in the signalRConnectionInfo binding is used to create an authenticated SignalR Service connection. 在本地开发期间,请将该属性保留为空。Leave the property blank for local development. 将函数应用部署到 Azure 时,将会使用该属性。You will use it when the function app is deployed to Azure.

  5. 打开 negotiate/index.js 查看函数的正文。Open negotiate/index.js to view the body of the function. 按如下所示修改该文件的内容。Modify the content of the file to the following.

    module.exports = async function (context, req, connectionInfo) {
        context.res.body = connectionInfo;
    };
    

    此函数从输入绑定中提取 SignalR 连接信息,并在 HTTP 响应正文中将此信息返回给客户端。This function takes the SignalR connection information from the input binding and returns it to the client in the HTTP response body. SignalR 客户端会使用此信息连接到 SignalR 服务实例。The SignalR client will use this information to connect to the SignalR Service instance.

创建用于发送聊天消息的函数Create a function to send chat messages

Web 应用还需要使用一个 HTTP API 来发送聊天消息。The web app also requires an HTTP API to send chat messages. 我们将创建名为 SendMessage 的 HTTP 触发的函数,用于通过 SignalR 服务将消息发送到所有连接的客户端。You will create an HTTP triggered function named SendMessage that sends messages to all connected clients using SignalR Service.

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure Functions: Create Function”命令。Search for and select the Azure Functions: Create Function command.

  3. 出现提示时,请提供以下信息。When prompted, provide the following information.

    NameName Value
    函数应用文件夹Function app folder 选择主项目文件夹select the main project folder
    模板Template HTTP 触发器HTTP Trigger
    NameName SendMessageSendMessage
    授权级别Authorization level 匿名Anonymous

    将创建包含新函数的名为 SendMessage 的文件夹。A folder named SendMessage is created that contains the new function.

  4. 打开 SendMessage/function.json 以配置函数的绑定。Open SendMessage/function.json to configure bindings for the function. 按如下所示修改该文件的内容。Modify the content of the file to the following.

    {
        "disabled": false,
        "bindings": [
            {
                "authLevel": "anonymous",
                "type": "httpTrigger",
                "direction": "in",
                "name": "req",
                "route": "messages",
                "methods": [
                    "post"
                ]
            },
            {
                "type": "http",
                "direction": "out",
                "name": "res"
            },
            {
                "type": "signalR",
                "name": "$return",
                "hubName": "chat",
                "direction": "out"
            }
        ]
    }
    

    这会对原始函数做出两项更改:This makes two changes to the original function:

    • 将路由更改为 messages,并将 HTTP 触发器限制为 POST HTTP 方法。Changes the route to messages and restricts the HTTP trigger to the POST HTTP method.
    • 添加 SignalR 服务输出绑定,用于将函数返回的消息发送到已连接至名为 chat 的 SignalR 服务中心的所有客户端。Adds a SignalR Service output binding that sends a message returned by the function to all clients connected to a SignalR Service hub named chat.
  5. 保存文件。Save the file.

  6. 打开 SendMessage/index.js 查看函数的正文。Open SendMessage/index.js to view the body of the function. 按如下所示修改该文件的内容。Modify the content of the file to the following.

    module.exports = async function (context, req) {
        const message = req.body;
        message.sender = req.headers && req.headers['x-ms-client-principal-name'] || '';
    
        let recipientUserId = '';
        if (message.recipient) {
            recipientUserId = message.recipient;
            message.isPrivate = true;
        }
    
        return {
            'userId': recipientUserId,
            'target': 'newMessage',
            'arguments': [ message ]
        };
    };
    

    此函数从 HTTP 请求中提取正文,并通过在连接到 SignalR 服务的每个客户端上调用名为 newMessage 的函数,将此正文发送到所有这些客户端。This function takes the body from the HTTP request and sends it to clients connected to SignalR Service, invoking a function named newMessage on each client.

    此函数可以读取发送者的标识,并可以接受消息正文中的 recipient 值,以便能够以私密的方式将消息发送到单个用户。The function can read the sender's identity and can accept a recipient value in the message body to allow for a message to be sent privately to a single user. 本教程稍后将使用这些功能。These functionalities will be used later in the tutorial.

  7. 保存文件。Save the file.

创建并运行聊天客户端 Web 用户界面Create and run the chat client web user interface

聊天应用程序的 UI 是使用 Vue JavaScript 框架创建的简单单页应用程序 (SPA)。The chat application's UI is a simple single page application (SPA) created with the Vue JavaScript framework. 该 UI 单独托管在函数应用中。It will be hosted separately from the function app. 在本地,我们将使用 Live Server VS Code 扩展运行 Web 界面。Locally, you will run the web interface using the Live Server VS Code extension.

  1. 在 VS Code 中,在主项目文件夹的根目录内创建名为 content 的新文件夹。In VS Code, create a new folder named content at the root of the main project folder.

  2. content 文件夹中创建名为 index.html 的新文件。In the content folder, create a new file named index.html.

  3. 复制并粘贴 index.html 的内容。Copy and paste the content of index.html.

  4. 保存文件。Save the file.

  5. F5 在本地运行函数应用,并附加一个调试程序。Press F5 to run the function app locally and attach a debugger.

  6. 打开 index.html 后,通过打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)并选择“Live Server: 使用 Live Server 打开”来启动 Live Server。With index.html open, start Live Server by opening the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P) and selecting Live Server: Open with Live Server. Live Server 将在浏览器中打开该应用程序。Live Server will open the application in a browser.

  7. 应用程序已打开。The application opens. 在聊天框中输入一条消息并按 Enter。Enter a message in the chat box and press enter. 刷新应用程序以查看新消息。Refresh the application to see new messages. 由于未配置身份验证,所有消息将以“匿名”方式发送。Because no authentication was configured, all messages will be sent as "anonymous".

部署到 Azure 并启用身份验证Deploy to Azure and enable authentication

我们一直在本地运行函数应用和聊天应用程序。You have been running the function app and chat application locally. 现在,我们将其部署到 Azure,并在应用程序中启用身份验证和私密消息传送。You will now deploy them to Azure and enable authentication and private messaging in the application.

使用 VS Code 登录到 AzureLog into Azure with VS Code

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure: Sign in”命令。Search for and select the Azure: Sign in command.

  3. 在浏览器中遵照说明完成登录过程。Follow the instructions to complete the sign in process in your browser.

创建存储帐户Create a Storage account

在 Azure 中运行的函数应用需要 Azure 存储帐户。An Azure Storage account is required by a function app running in Azure. 你还会使用 Azure 存储的静态网站功能托管聊天 UI 的网页。You will also host the web page for the chat UI using the static websites feature of Azure Storage.

  1. 在 Azure 门户中,单击用于创建新 Azure 资源的“创建资源”(+ ) 按钮。 In the Azure portal, click on the Create a resource (+) button for creating a new Azure resource.

  2. 选择“存储” 类别,然后选择“存储帐户” 。Select the Storage category, then select Storage account.

  3. 输入以下信息。Enter the following information.

    NameName Value
    SubscriptionSubscription 选择包含 SignalR 服务实例的订阅Select the subscription containing the SignalR Service instance
    Resource groupResource group 选择相同资源组Select the same resource group
    资源名称Resource name 存储帐户的唯一名称A unique name for the Storage account
    位置Location 选择其他资源所在的同一位置Select the same location as your other resources
    性能Performance 标准Standard
    帐户类型Account kind StorageV2(常规用途 V2)StorageV2 (general purpose V2)
    复制Replication 本地冗余存储 (LRS)Locally-redundant storage (LRS)
    访问层Access Tier Hot
  4. 单击“查看 + 创建” ,然后单击“创建” 。Click Review + create, then Create.

配置静态网站Configure static websites

  1. 创建存储帐户后,在 Azure 门户中打开它。After the Storage account is created, open it in the Azure portal.

  2. 选择“静态网站” 。Select Static website.

  3. 选择“启用”以启用静态网站功能。 Select Enabled to enable the static website feature.

  4. 在“索引文档名称” 中,输入 index.html 。In Index document name, enter index.html.

  5. 单击“ 保存”。Click Save.

  6. “主终结点” 随即出现。A Primary endpoint appears. 请记下此值。Note this value. 配置函数应用需要它。It will be required to configure the function app.

为函数应用配置身份验证Configure function app for authentication

到目前为止,聊天应用程序以匿名方式工作。So far, the chat app works anonymously. 在 Azure 中,我们将使用应用服务身份验证来验证用户的身份。In Azure, you will use App Service Authentication to authenticate the user. 可将已经过身份验证的用户的用户 ID 或用户名传递给 SignalRConnectionInfo 绑定,以生成进行用户身份验证时所需的连接信息。The user ID or username of the authenticated user can be passed to the SignalRConnectionInfo binding to generate connection information that is authenticated as the user.

发送消息时,应用可以确定是要发送到所有已连接的客户端,还是仅发送到已对给定用户进行身份验证的客户端。When a sending message, the app can decide whether to send it to all connected clients, or only to the clients that have been authenticated to a given user.

  1. 在 VS Code 中打开 negotiate/function.jsonIn VS Code, open negotiate/function.json.

  2. 将一个绑定表达式插入到 SignalRConnectionInfo 绑定的 userId 属性中:{headers.x-ms-client-principal-name}Insert a binding expression into the userId property of the SignalRConnectionInfo binding: {headers.x-ms-client-principal-name}. 这会将值设置为经过身份验证的用户的用户名。This sets the value to the username of the authenticated user. 特性现在应如下所示。The attribute should now look like this.

    {
        "type": "signalRConnectionInfo",
        "name": "connectionInfo",
        "userId": "{headers.x-ms-client-principal-name}",
        "hubName": "chat",
        "direction": "in"
    }
    
  3. 保存文件。Save the file.

将函数应用部署到 AzureDeploy function app to Azure

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P),然后选择“Azure Functions: 部署到函数应用”。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P) and select Azure Functions: Deploy to Function App.

  2. 出现提示时,请提供以下信息。When prompted, provide the following information.

    NameName Value
    要部署的文件夹Folder to deploy 选择主项目文件夹Select the main project folder
    SubscriptionSubscription 选择订阅Select your subscription
    函数应用Function app 选择“创建新函数应用” Select Create New Function App
    函数应用名称Function app name 输入唯一的名称Enter a unique name
    Resource groupResource group 选择 SignalR 服务实例所在的同一资源组Select the same resource group as the SignalR Service instance
    存储帐户Storage account 选择前面创建的存储帐户Select the storage account you created earlier

    随即会在 Azure 中创建新的函数应用,并开始部署。A new function app is created in Azure and the deployment begins. 等待部署完成。Wait for the deployment to complete.

上传函数应用本地设置Upload function app local settings

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure Functions: 上传本地设置”命令。Search for and select the Azure Functions: Upload local settings command.

  3. 出现提示时,请提供以下信息。When prompted, provide the following information.

    NameName Value
    本地设置文件Local settings file local.settings.jsonlocal.settings.json
    SubscriptionSubscription 选择订阅Select your subscription
    函数应用Function app 选择前面部署的函数应用Select the previously deployed function app

本地设置将上传到 Azure 中的函数应用。Local settings are uploaded to the function app in Azure. 如果系统提示是否要覆盖现有设置,请选择“全是”。 If prompted to overwrite existing settings, select Yes to all.

启用应用服务身份验证Enable App Service Authentication

应用服务身份验证支持使用 Azure Active Directory、Facebook、Twitter、Microsoft 帐户和 Google 的身份验证。App Service Authentication supports authentication with Azure Active Directory, Facebook, Twitter, Microsoft account, and Google.

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure Functions: 在门户中打开”命令。Search for and select the Azure Functions: Open in portal command.

  3. 选择订阅和函数应用的名称,在 Azure 门户中打开该函数应用。Select the subscription and function app name to open the function app in the Azure portal.

  4. 在已在门户中打开的函数应用中,找到“平台功能”选项卡,并选择“身份验证/授权”。 In the function app that was opened in the portal, locate the Platform features tab, select Authentication/Authorization.

  5. 启用应用服务身份验证。 Turn On App Service Authentication.

  6. 在“请求未经过身份验证时需执行的操作”中,选择“使用 {前面选择的身份验证提供程序} 登录”。 In Action to take when request is not authenticated, select "Log in with {authentication provider you selected earlier}".

  7. 在“允许的外部重定向 URL”中,输入前面记下的存储帐户主要 Web 终结点的 URL。 In Allowed External Redirect URLs, enter the URL of your storage account primary web endpoint that you previously noted.

  8. 遵循所选登录提供程序的文档完成配置。Follow the documentation for the login provider of your choice to complete the configuration.

更新 Web 应用Update the web app

  1. 在 Azure 门户中,导航到函数应用的概述页。In the Azure portal, navigate to the function app's overview page.

  2. 复制函数应用的 URL。Copy the function app's URL.

    获取 URL

  3. 在 VS Code 中打开 index.html,并将 apiBaseUrl 的值替换为函数应用的 URL。In VS Code, open index.html and replace the value of apiBaseUrl with the function app's URL.

  4. 可以使用 Azure Active Directory、Facebook、Twitter、Microsoft 帐户或 Google 为应用程序配置身份验证。The application can be configured with authentication using Azure Active Directory, Facebook, Twitter, Microsoft account, or Google. 通过设置 authProvider 的值来选择要使用的身份验证提供程序。Select the authentication provider that you will use by setting the value of authProvider.

  5. 保存文件。Save the file.

将 Web 应用程序部署到 Blob 存储Deploy the web application to blob storage

将使用 Azure Blob 存储的静态网站功能托管 Web 应用程序。The web application will be hosted using Azure Blob Storage's static websites feature.

  1. 打开 VS Code 命令面板(Windows 快捷键为 Ctrl-Shift-P,macOS 快捷键为 Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜索并选择“Azure 存储: 部署到静态网站”命令。Search for and select the Azure Storage: Deploy to Static Website command.

  3. 输入以下值:Enter the following values:

    NameName Value
    SubscriptionSubscription 选择订阅Select your subscription
    存储帐户Storage account 选择前面创建的存储帐户Select the storage account you created earlier
    要部署的文件夹Folder to deploy 选择“浏览” ,然后选择“内容” 文件夹Select Browse and select the content folder

“内容” 文件夹中的文件现在应部署到静态网站。The files in the content folder should now be deployed to the static website.

启用函数应用跨域资源共享 (CORS)Enable function app cross origin resource sharing (CORS)

尽管 local.settings.json 中有一个 CORS 设置,但该设置不会传播到 Azure 中的函数应用。Although there is a CORS setting in local.settings.json, it is not propagated to the function app in Azure. 需要单独设置此项。You need to set it separately.

  1. 在 Azure 门户中打开函数应用。Open the function app in the Azure portal.

  2. 在“平台功能” 选项卡下,选择“CORS” 。Under the Platform features tab, select CORS.

    找到“CORS”

  3. 在“允许的来源” 部分中,添加一个将静态网站项主终结点 作为值的条目(删除尾部 / )。In the Allowed origins section, add an entry with the static website primary endpoint as the value (remove the trailing /).

  4. 为了使 SignalR JavaScript SDK 可从浏览器调用函数应用,必须启用 CORS 中对凭据的支持。In order for the SignalR JavaScript SDK call your function app from a browser, support for credentials in CORS must be enabled. 选中“启用 Access-Control-Allow-Credentials”复选框。Select the "Enable Access-Control-Allow-Credentials" checkbox.

    启用 Access-Control-Allow-Credentials

  5. 单击“保存”以保存 CORS 设置 。Click Save to persist the CORS settings.

尝试运行应用程序Try the application

  1. 在浏览器中,导航到存储帐户的主要 Web 终结点。In a browser, navigate to the storage account's primary web endpoint.

  2. 选择“登录”,使用所选的身份验证提供程序进行身份验证。 Select Login to authenticate with your chosen authentication provider.

  3. 在主要聊天框中输入公共消息并发送这些消息。Send public messages by entering them into the main chat box.

  4. 单击聊天历史记录中的用户名发送私人消息。Send private messages by clicking on a username in the chat history. 只有选定的接收者可以收到这些消息。Only the selected recipient will receive these messages.

祝贺你!Congratulations! 现已部署一个实时无服务器聊天应用!You have deployed a real-time, serverless chat app!

演示

清理资源Clean up resources

若要清理本教程创建的资源,请使用 Azure 门户删除相应的资源组。To clean up the resources created in this tutorial, delete the resource group using the Azure portal.

后续步骤Next steps

本教程已介绍如何将 Azure Functions 与 Azure SignalR 服务配合使用。In this tutorial, you learned how to use Azure Functions with Azure SignalR Service. 接下来请详细了解如何使用 Azure Functions 的 SignalR 服务绑定来生成实时无服务器应用程序。Read more about building real-time serverless applications with SignalR Service bindings for Azure Functions.