使用 Azure SignalR Service Azure Functions 開發和設定Azure Functions development and configuration with Azure SignalR Service

Azure Functions 應用程式可以利用Azure SignalR Service系結來新增即時功能。Azure Functions applications can leverage the Azure SignalR Service bindings to add real-time capabilities. 用戶端應用程式會使用數種語言提供的用戶端 Sdk 來連接 Azure SignalR Service 並接收即時訊息。Client applications use client SDKs available in several languages to connect to Azure SignalR Service and receive real-time messages.

本文說明開發和設定與 SignalR Service 整合的 Azure 函式應用程式的概念。This article describes the concepts for developing and configuring an Azure Function app that is integrated with SignalR Service.

SignalR Service 設定SignalR Service configuration

Azure SignalR Service 可以在不同的模式下設定。Azure SignalR Service can be configured in different modes. 與 Azure Functions 搭配使用時, 服務必須以無伺服器模式設定。When used with Azure Functions, the service must be configured in Serverless mode.

在 Azure 入口網站中, 找出您 SignalR Service 資源的 設定 頁面。In the Azure portal, locate the Settings page of your SignalR Service resource. 將 [服務模式] 設定為 [無伺服器]。Set the Service mode to Serverless.

SignalR Service 模式

Azure Functions 開發Azure Functions development

以 Azure Functions 和 Azure SignalR Service 建立的無伺服器即時應用程式通常需要兩個 Azure Functions:A serverless real-time application built with Azure Functions and Azure SignalR Service typically requires two Azure Functions:

  • 用戶端呼叫的「negotiate」函式, 以取得有效的 SignalR Service 存取權杖和服務端點 URLA "negotiate" function that the client calls to obtain a valid SignalR Service access token and service endpoint URL
  • 傳送訊息或管理群組成員資格的一或多個函式One or more functions that send messages or manage group membership

negotiate 函式negotiate function

用戶端應用程式需要有效的存取權杖, 才能連接到 Azure SignalR Service。A client application requires a valid access token to connect to Azure SignalR Service. 存取權杖可以是匿名或通過指定的使用者識別碼驗證。An access token can be anonymous or authenticated to a given user ID. 無伺服器 SignalR Service 應用程式需要名為「negotiate」的 HTTP 端點, 才能取得權杖和其他連接資訊, 例如 SignalR Service 端點 URL。Serverless SignalR Service applications require an HTTP endpoint named "negotiate" to obtain a token and other connection information, such as the SignalR Service endpoint URL.

使用 HTTP 觸發的 Azure 函數和SignalRConnectionInfo輸入系結來產生連接資訊物件。Use an HTTP triggered Azure Function and the SignalRConnectionInfo input binding to generate the connection information object. 函式必須具有以結尾/negotiate的 HTTP 路由。The function must have an HTTP route that ends in /negotiate.

如需有關如何建立 negotiate 函式的詳細資訊, 請參閱 SignalRConnectionInfo輸入系結參考。For more information on how to create the negotiate function, see the SignalRConnectionInfo input binding reference.

若要瞭解如何建立已驗證的權杖, 請參閱使用 App Service 驗證To learn about how to create an authenticated token, refer to Using App Service Authentication.

傳送訊息和管理群組成員資格Sending messages and managing group membership

使用SignalR輸出系結, 將訊息傳送至連線至 Azure SignalR Service 的用戶端。Use the SignalR output binding to send messages to clients connected to Azure SignalR Service. 您可以將訊息廣播到所有用戶端, 也可以將它們傳送到以特定使用者識別碼驗證或已新增至特定群組的用戶端子集。You can broadcast messages to all clients, or you can send them to a subset of clients that are authenticated with a specific user ID or have been added to a specific group.

使用者可以新增至一個或多個群組。Users can be added to one or more groups. 您也可以使用SignalR輸出系結, 在群組中新增或移除使用者。You can also use the SignalR output binding to add or remove users to/from groups.

如需詳細資訊, 請參閱 SignalR輸出系結參考。For more information, see the SignalR output binding reference.

SignalR 中樞SignalR Hubs

SignalR 具有「中樞」的概念。SignalR has a concept of "hubs". 每個用戶端連線以及從 Azure Functions 傳送的每個訊息都是以特定的中樞為範圍。Each client connection and each message sent from Azure Functions is scoped to a specific hub. 您可以使用中樞做為將連線和訊息分隔成邏輯命名空間的方式。You can use hubs as a way to separate your connections and messages into logical namespaces.

用戶端開發Client development

SignalR 用戶端應用程式可以利用其中一種語言的 SignalR 用戶端 SDK, 輕鬆地連線到 Azure SignalR Service 並從中接收訊息。SignalR client applications can leverage the SignalR client SDK in one of several languages to easily connect to and receive messages from Azure SignalR Service.

設定用戶端連接Configuring a client connection

若要連接到 SignalR Service, 用戶端必須完成由下列步驟所組成的成功連線協調:To connect to SignalR Service, a client must complete a successful connection negotiation that consists of these steps:

  1. 對上述的negotiate HTTP 端點提出要求, 以取得有效的連接資訊Make a request to the negotiate HTTP endpoint discussed above to obtain valid connection information
  2. 使用從negotiate端點取得的服務端點 URL 和存取權杖, 連接到 SignalR ServiceConnect to SignalR Service using the service endpoint URL and access token obtained from the negotiate endpoint

SignalR 用戶端 Sdk 已包含執行協調交握所需的邏輯。SignalR client SDKs already contain the logic required to perform the negotiation handshake. 將 negotiate 端點的 URL (減去negotiate區段) 傳遞至 SDK 的。 HubConnectionBuilderPass the negotiate endpoint's URL, minus the negotiate segment, to the SDK's HubConnectionBuilder. 以下是 JavaScript 的範例:Here is an example in JavaScript:

const connection = new signalR.HubConnectionBuilder()
  .withUrl('https://my-signalr-function-app.azurewebsites.net/api')
  .build()

依照慣例, SDK 會自動附加/negotiate至 URL, 並使用它來開始進行協商。By convention, the SDK automatically appends /negotiate to the URL and uses it to begin the negotiation.

注意

如果您在瀏覽器中使用 JavaScript/TypeScript SDK, 您需要在您的函數應用程式上啟用跨原始來源資源分享 (CORS)If you are using the JavaScript/TypeScript SDK in a browser, you need to enable cross-origin resource sharing (CORS) on your Function App.

如需有關如何使用 SignalR 用戶端 SDK 的詳細資訊, 請參閱您語言的檔:For more information on how to use the SignalR client SDK, refer to the documentation for your language:

從用戶端傳送訊息至服務Sending messages from a client to the service

雖然 SignalR SDK 可讓用戶端應用程式叫用 SignalR 中樞的後端邏輯, 但當您搭配 Azure Functions 使用 SignalR Service 時, 尚不支援這項功能。Although the SignalR SDK allows client applications to invoke backend logic in a SignalR hub, this functionality is not yet supported when you use SignalR Service with Azure Functions. 使用 HTTP 要求叫用 Azure Functions。Use HTTP requests to invoke Azure Functions.

Azure Functions 設定Azure Functions configuration

與 Azure SignalR Service 整合的 azure 函式應用程式可以像任何一般 Azure 函式應用程式一樣部署, 方法是使用持續部署zip 部署從封裝執行等技術。Azure Function apps that integrate with Azure SignalR Service can be deployed like any typical Azure Function app, using techniques such as continuously deployment, zip deployment, and run from package.

不過, 使用 SignalR Service 系結的應用程式有幾個特殊考慮。However, there are a couple of special considerations for apps that use the SignalR Service bindings. 如果用戶端在瀏覽器中執行, 則必須啟用 CORS。If the client runs in a browser, CORS must be enabled. 而且, 如果應用程式需要驗證, 您可以將 negotiate 端點與 App Service Authentication 整合。And if the app requires authentication, you can integrate the negotiate endpoint with App Service Authentication.

啟用 CORSEnabling CORS

JavaScript/TypeScript 用戶端會向 negotiate 函式發出 HTTP 要求, 以起始連接協商。The JavaScript/TypeScript client makes HTTP requests to the negotiate function to initiate the connection negotiation. 當用戶端應用程式裝載于與 Azure Function 應用程式不同的網域時, 必須在函數應用程式上啟用跨原始來源資源分享 (CORS), 否則瀏覽器將會封鎖要求。When the client application is hosted on a different domain than the Azure Function app, cross-origin resource sharing (CORS) must be enabled on the Function app or the browser will block the requests.

發出Localhost

在您的本機電腦上執行Host函式應用程式時, 您可以將區段新增至本機. 設定, 以啟用 CORS。When running the Function app on your local computer, you can add a Host section to local.settings.json to enable CORS. Host在區段中, 新增兩個屬性:In the Host section, add two properties:

  • CORS-輸入做為用戶端應用程式來源的基底 URLCORS - enter the base URL that is the origin the client application
  • CORSCredentials-將它設定true為以允許 "withCredentials" 要求CORSCredentials - set it to true to allow "withCredentials" requests

範例:Example:

{
  "IsEncrypted": false,
  "Values": {
    // values
  },
  "Host": {
    "CORS": "http://localhost:8080",
    "CORSCredentials": true
  }
}

雲端 Azure Functions CORSCloud - Azure Functions CORS

若要在 Azure 函式應用程式上啟用 CORS, 請移至 Azure 入口網站中函數應用程式的 [平臺功能] 索引標籤下的 [cors 設定] 畫面。To enable CORS on an Azure Function app, go to the CORS configuration screen under the Platform features tab of your Function app in the Azure portal.

注意

Azure Functions Linux 使用量計畫中尚未提供 CORS 設定。CORS configuration is not yet available in Azure Functions Linux Consumption plan. 使用AZURE API 管理來啟用 CORS。Use Azure API Management to enable CORS.

必須啟用 SignalR 用戶端的 CORS, 才能呼叫 negotiate 函式。CORS with Access-Control-Allow-Credentials must be enabled for the SignalR client to call the negotiate function. 選取核取方塊以啟用它。Select the checkbox to enable it.

在 [允許的來源] 區段中, 使用 web 應用程式的原始基底 URL 來新增專案。In the Allowed origins section, add an entry with the origin base URL of your web application.

設定 CORS

雲端-Azure API 管理Cloud - Azure API Management

Azure API 管理提供可將功能新增至現有後端服務的 API 閘道。Azure API Management provides an API gateway that adds capabilities to existing back-end services. 您可以使用它將 CORS 新增至您的函數應用程式。You can use it to add CORS to your function app. 它提供的取用量層具有按動作付費的定價和每月免費授與。It offers a consumption tier with pay-per-action pricing and a monthly free grant.

如需如何匯入 Azure 函數應用程式的相關資訊, 請參閱 API 管理檔。Refer to the API Management documentation for information on how to import an Azure Function app. 匯入之後, 您可以新增輸入原則, 以啟用具有存取控制-允許憑證支援的 CORS。Once imported, you can add an inbound policy to enable CORS with Access-Control-Allow-Credentials support.

<cors allow-credentials="true">
  <allowed-origins>
    <origin>https://azure-samples.github.io</origin>
  </allowed-origins>
  <allowed-methods>
    <method>GET</method>
    <method>POST</method>
  </allowed-methods>
  <allowed-headers>
    <header>*</header>
  </allowed-headers>
  <expose-headers>
    <header>*</header>
  </expose-headers>
</cors>

將您的 SignalR 用戶端設定為使用 API 管理 URL。Configure your SignalR clients to use the API Management URL.

使用 App Service 驗證Using App Service Authentication

Azure Functions 具有內建的驗證, 可支援 Facebook、Twitter、Microsoft 帳戶、Google 和 Azure Active Directory 等熱門提供者。Azure Functions has built-in authentication, supporting popular providers such as Facebook, Twitter, Microsoft Account, Google, and Azure Active Directory. 這項功能可以與SignalRConnectionInfo系結整合, 以建立與已驗證使用者識別碼之 Azure SignalR Service 的連接。This feature can be integrated with the SignalRConnectionInfo binding to create connections to Azure SignalR Service that have been authenticated to a user ID. 您的應用程式可以使用以該使用者識別碼為目標的SignalR輸出系結來傳送訊息。Your application can send messages using the SignalR output binding that are targeted to that user ID.

在 Azure 入口網站的函數應用程式的 [平臺功能] 索引標籤中, 開啟 [驗證/授權設定] 視窗。In the Azure portal, in your Function app's Platform features tab, open the Authentication/authorization settings window. 遵循App Service 驗證的檔, 使用您選擇的身分識別提供者來設定驗證。Follow the documentation for App Service Authentication to configure authentication using an identity provider of your choice.

一旦設定之後, 經過驗證的 HTTP x-ms-client-principal-name要求x-ms-client-principal-id將會包含和標頭, 分別包含已驗證身分識別的使用者名稱和使用者識別碼。Once configured, authenticated HTTP requests will include x-ms-client-principal-name and x-ms-client-principal-id headers containing the authenticated identity's username and user ID, respectively.

您可以在SignalRConnectionInfo系結設定中使用這些標頭來建立已驗證的連接。You can use these headers in your SignalRConnectionInfo binding configuration to create authenticated connections. 以下是使用x-ms-client-principal-id標C#頭的範例 negotiate 函式。Here is an example C# negotiate function that uses the x-ms-client-principal-id header.

[FunctionName("negotiate")]
public static SignalRConnectionInfo Negotiate(
    [HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req,
    [SignalRConnectionInfo
        (HubName = "chat", UserId = "{headers.x-ms-client-principal-id}")]
        SignalRConnectionInfo connectionInfo)
{
    // connectionInfo contains an access key token with a name identifier claim set to the authenticated user
    return connectionInfo;
}

接著, 您可以藉由設定UserId SignalR 訊息的屬性, 將訊息傳送給該使用者。You can then send messages to that user by setting the UserId property of a SignalR message.

[FunctionName("SendMessage")]
public static Task SendMessage(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message,
    [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            // the message will only be sent to these user IDs
            UserId = "userId1",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

如需其他語言的詳細資訊, 請參閱 Azure Functions 參考的Azure SignalR Service系結。For information on other languages, see the Azure SignalR Service bindings for Azure Functions reference.

後續步驟Next steps

在本文中, 您已瞭解如何使用 Azure Functions 開發和設定無伺服器 SignalR Service 應用程式。In this article, you have learned how to develop and configure serverless SignalR Service applications using Azure Functions. 嘗試使用 [SignalR Service 總覽] 頁面上的其中一個 [快速入門] 或 [教學課程] 自行建立應用程式。Try creating an application yourself using one of the quick starts or tutorials on the SignalR Service overview page.