Azure Functions 開發和使用 Azure SignalR 服務的組態Azure Functions development and configuration with Azure SignalR Service

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

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

SignalR 服務組態SignalR Service configuration

Azure SignalR 服務可以設定在不同的模式。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 服務資源頁面。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 服務通常所建置的無伺服器即時應用程式需要兩個 Azure 函式:A serverless real-time application built with Azure Functions and Azure SignalR Service typically requires two Azure Functions:

  • 「 交涉 」 以取得有效的 SignalR 服務的用戶端呼叫的函式的存取權杖,而服務端點 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 function

用戶端應用程式需要有效的存取權杖來連線到 Azure SignalR 服務。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 服務應用程式必須將 HTTP 端點名為"negotiate"來取得權杖和其他的連接資訊,例如 SignalR 服務端點 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. 此函式必須以 HTTP 路由/negotiateThe function must have an HTTP route that ends in /negotiate.

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

若要深入了解如何建立已驗證的 token,請參閱使用 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 服務。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 服務訊息。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 服務,用戶端必須完成下列步驟所組成的連線成功交涉:To connect to SignalR Service, a client must complete a successful connection negotiation that consists of these steps:

  1. 提出的要求交涉上面討論以取得有效的連接資訊的 HTTP 端點Make a request to the negotiate HTTP endpoint discussed above to obtain valid connection information
  2. 使用連線到 SignalR 服務的服務端點 URL 和存取權杖將會取自交涉端點Connect 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 服務時。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 函式。Use HTTP requests to invoke Azure Functions.

Azure Functions 組態Azure Functions configuration

整合 Azure SignalR 服務的 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 服務的繫結的應用程式的特殊考量。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 驗證。And if the app requires authentication, you can integrate the negotiate endpoint with App Service Authentication.

啟用 CORSEnabling CORS

JavaScript/TypeScript 用戶端會將 HTTP 要求對交涉函式,來起始連線交涉。The JavaScript/TypeScript client makes HTTP requests to the negotiate function to initiate the connection negotiation. 當用戶端應用程式裝載於 Azure 函數應用程式不同的網域時,必須在函式應用程式上啟用跨原始資源共用 (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.

localhostLocalhost

當您的本機電腦上執行函式應用程式,您可以加入Host一節local.settings.json來啟用 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
  }
}

AzureAzure

若要啟用 CORS 的 Azure 函式應用程式上,移至下的 [CORS 組態] 畫面平台功能函式應用程式在 Azure 入口網站中的索引標籤。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.

SignalR 用戶端呼叫交涉函式時,必須啟用 CORS 的存取控制-允許-認證使用。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

使用 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 服務已通過驗證的使用者識別碼。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-namex-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. 以下是範例C#交涉使用函式x-ms-client-principal-id標頭。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;
}

您可以再將訊息傳送給該使用者藉由設定UserIdSignalR 訊息的屬性。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 SignalR 服務繫結for Azure Functions 的參考。For information on other languages, see the Azure SignalR Service bindings for Azure Functions reference.

後續步驟Next steps

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