教學課程:使用 Azure Functions 進行 Azure SignalR 服務驗證Tutorial: Azure SignalR Service authentication with Azure Functions

此教學課程將逐步解說如何使用 Azure Functions、App Service 驗證和 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 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 Service 模式

初始化函式應用程式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. 從功能表中選取 [檢視] > [命令選擇區] (快速鍵 Ctrl-Shift-P,macOS:Cmd-Shift-P),以在 VS Code 中開啟命令選擇區。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:建立新專案] 命令,並加以選取。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
        }
    }
    
    • 將 Azure SignalR 服務連接字串輸入名為 AzureSignalRConnectionString 的設定中。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 命令選擇區 (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: 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. 這會新增輸入繫結,為用戶端產生用來連線至 Azure SignalR 服務中樞 chat 的有效認證。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 Service 執行個體。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 命令選擇區 (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: 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 Service 輸出繫結,以將函式所傳回訊息傳送給所有已連線至 SignalR Service 中樞 chat 的用戶端。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.

    此函式可讀取寄件者的身分識別,並可接受訊息本文中的收件者值,讓訊息能夠私下傳送給單一使用者。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. 它會與函式應用程式分開來裝載。It will be hosted separately from the function app. 在本機上,您將使用即時伺服器 VS Code 擴充功能來執行 Web 介面。Locally, you will run the web interface using the Live Server VS Code extension.

  1. 在 VS Code 中,請在主要專案資料夾的根目錄建立名為內容的新資料夾。In VS Code, create a new folder named content at the root of the main project folder.

  2. 內容資料夾中,建立名為 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 命令選擇區 (Ctrl-Shift-P,macOS:Cmd-Shift-P),然後選取 [即時伺服器:開啟即時伺服器],以啟動即時伺服器。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 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 命令選擇區 (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: 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
    訂用帳戶Subscription 選取包含 SignalR Service 執行個體的訂用帳戶Select the subscription containing the SignalR Service instance
    資源群組Resource 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.htmlIn 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 中,您將使用 App Service 驗證來驗證使用者。In Azure, you will use App Service Authentication to authenticate the user. 已驗證的使用者所使用的使用者識別碼或使用者名稱可傳至 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 命令選擇區 (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
    訂用帳戶Subscription 選取您的訂用帳戶Select your subscription
    函式應用程式Function app 選取 [建立新的函式應用程式]Select Create New Function App
    函式應用程式名稱Function app name 輸入唯一名稱Enter a unique name
    資源群組Resource 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 命令選擇區 (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
    訂用帳戶Subscription 選取您的訂用帳戶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.

啟用 App Service 驗證Enable App Service Authentication

App Service 驗證支援以 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 命令選擇區 (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. 開啟 App Service 驗證。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

Web 應用程式會使用 Azure Blob 儲存體的靜態網站功能進行裝載。The web application will be hosted using Azure Blob Storage's static websites feature.

  1. 開啟 VS Code 命令選擇區 (Ctrl-Shift-P,macOS:Cmd-Shift-P)。Open the VS Code command palette (Ctrl-Shift-P, macOS: Cmd-Shift-P).

  2. 搜尋並選取 [Azure Storage:Deploy to Static Website] (Azure 儲存體: 部署至靜態網站) 命令。Search for and select the Azure Storage: Deploy to Static Website command.

  3. 輸入下列值:Enter the following values:

    NameName Value
    訂用帳戶Subscription 選取您的訂用帳戶Select your subscription
    儲存體帳戶Storage account 選取您稍早建立的儲存體帳戶Select the storage account you created earlier
    要部署的資料夾Folder to deploy 依序選取 [瀏覽] 和 [content] 資料夾Select Browse and select the content folder

[content] 資料夾中的檔案現在應該已部署至靜態網站。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 Service 繫結建置即時無伺服器應用程式。Read more about building real-time serverless applications with SignalR Service bindings for Azure Functions.