適用於 Azure Functions 的 SignalR Service 繫結SignalR Service bindings for Azure Functions

本文說明如何藉由在 Azure Functions 中使用 SignalR Service 繫結,來驗證及傳送即時訊息給連線至 Azure SignalR Service 的用戶端。This article explains how to authenticate and send real-time messages to clients connected to Azure SignalR Service by using SignalR Service bindings in Azure Functions. Azure Functions 支援 SignalR Service 的輸入和輸出繫結。Azure Functions supports input and output bindings for SignalR Service.

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

封裝-函數2.x 和更新版本Packages - Functions 2.x and higher

Microsoft.signalrservice NuGet 套件(版本 1. *)中提供了 SignalR Service 系結。The SignalR Service bindings are provided in the Microsoft.Azure.WebJobs.Extensions.SignalRService NuGet package, version 1.*. 套件的原始程式碼位於 azure-functions-signalrservice-extension GitHub 存放庫中。Source code for the package is in the azure-functions-signalrservice-extension GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 新增支援To add support
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#Local development - C# script, JavaScript, F# 註冊擴充功能Register the extension
入口網站開發Portal development 註冊擴充功能Register the extension

若要了解如何在不重新發行您的函數應用程式專案的情況下在入口網站中更新現有的繫結延伸模組,請參閱更新您的延伸模組To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

如需如何設定及使用 SignalR Service 和 Azure Functions 的詳細資訊,請參閱Azure SignalR Service 的 Azure Functions 開發和設定。For details on how to configure and use SignalR Service and Azure Functions together, refer to Azure Functions development and configuration with Azure SignalR Service.

注釋程式庫(僅限 JAVA)Annotations library (Java only)

若要使用 JAVA 函式中的 SignalR Service 批註,您必須將相依性新增至您的 pom 的SignalR成品(1.0 版或更高版本)。To use the SignalR Service annotations in Java functions, you need to add a dependency to the azure-functions-java-library-signalr artifact (version 1.0 or higher) to your pom.xml.

<dependency>
    <groupId>com.microsoft.azure.functions</groupId>
    <artifactId>azure-functions-java-library-signalr</artifactId>
    <version>1.0.0</version>
</dependency>

輸入Input

在用戶端可以連線到 Azure SignalR Service 之前,它必須擷取服務端點 URL 和有效的存取權杖。Before a client can connect to Azure SignalR Service, it must retrieve the service endpoint URL and a valid access token. SignalRConnectionInfo 輸入繫結會產生 SignalR Service 端點 URL 和有效的存取權杖,可用來連線到服務。The SignalRConnectionInfo input binding produces the SignalR Service endpoint URL and a valid token that are used to connect to the service. 因為權杖是限時的,且可用來驗證連線的特定使用者,所以您不應該快取權杖或者在用戶端之間共用權杖。Because the token is time-limited and can be used to authenticate a specific user to a connection, you should not cache the token or share it between clients. 使用此繫結的 HTTP 觸發程序可以供用戶端用來擷取連線資訊。An HTTP trigger using this binding can be used by clients to retrieve the connection information.

如需如何使用此系結來建立可供 SignalR 用戶端 SDK 使用的「negotiate」函式的詳細資訊,請參閱 SignalR Service 概念檔中的Azure Functions 開發和設定一文。For more information on how this binding is used to create a "negotiate" function that can be consumed by a SignalR client SDK, see the Azure Functions development and configuration article in the SignalR Service concepts documentation.

下列範例示範 C# 函式,該函式會使用輸入繫結來取得 SignalR 連線資訊,並且透過 HTTP 傳回。The following example shows a C# function that acquires SignalR connection information using the input binding and returns it over HTTP.

[FunctionName("negotiate")]
public static SignalRConnectionInfo Negotiate(
    [HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req,
    [SignalRConnectionInfo(HubName = "chat")]SignalRConnectionInfo connectionInfo)
{
    return connectionInfo;
}

已驗證權杖Authenticated tokens

如果函式是由已驗證的用戶端觸發,您可以將使用者識別碼宣告新增至產生的權杖。If the function is triggered by an authenticated client, you can add a user ID claim to the generated token. 您可以使用App Service authentication,輕鬆地將驗證新增至函數應用程式。You can easily add authentication to a function app using App Service Authentication.

App Service 驗證會設定名為 x-ms-client-principal-idx-ms-client-principal-name 的 HTTP 標頭,這些標頭分別包含已驗證使用者的用戶端主體識別碼和名稱。App Service Authentication sets HTTP headers named x-ms-client-principal-id and x-ms-client-principal-name that contain the authenticated user's client principal ID and name, respectively.

您可以使用繫結運算式{headers.x-ms-client-principal-id}{headers.x-ms-client-principal-name},將繫結的 UserId 屬性設為任一標頭的值。You can set the UserId property of the binding to the value from either header using a binding expression: {headers.x-ms-client-principal-id} or {headers.x-ms-client-principal-name}.

[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;
}

輸出Output

若使用 SignalR 輸出繫結,即可使用 Azure SignalR Service 來傳送一或多則訊息。Use the SignalR output binding to send one or more messages using Azure SignalR Service. 您可以將訊息廣播到所有已連線的用戶端,或者您可以只將訊息廣播到已對指定使用者驗證的已連線用戶端。You can broadcast a message to all connected clients, or you can broadcast it only to connected clients that have been authenticated to a given user.

您也可以使用它來管理使用者所屬的群組。You can also use it to manage the groups that a user belongs to.

廣播到所有用戶端Broadcast to all clients

下列範例顯示的函式會使用輸出系結,將訊息傳送至所有已連線的用戶端。The following example shows a function that sends a message using the output binding to all connected clients. 目標是要在每個用戶端上叫用之方法的名稱。The target is the name of the method to be invoked on each client. 引數是零個或多個要傳遞至用戶端方法之物件的陣列。Arguments is an array of zero or more objects to be passed to the client method.

[FunctionName("SendMessage")]
public static Task SendMessage(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message, 
    [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage 
        {
            Target = "newMessage", 
            Arguments = new [] { message } 
        });
}

傳送給使用者Send to a user

您只能將訊息傳送至已通過使用者驗證的連線,方法是在 SignalR 訊息中設定使用者識別碼You can send a message only to connections that have been authenticated to a user by setting the user ID in the 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 this user ID
            UserId = "userId1",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

傳送至群組Send to a group

您可以藉由設定 SignalR 訊息中的組名,僅將訊息傳送至已新增至群組的連接。You can send a message only to connections that have been added to a group by setting the group name in the 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 be sent to the group with this name
            GroupName = "myGroup",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

群組管理Group management

SignalR Service 可讓使用者新增至群組。SignalR Service allows users to be added to groups. 然後可以將訊息傳送給群組。Messages can then be sent to a group. 您可以使用 SignalR 輸出系結來管理使用者的群組成員資格。You can use the SignalR output binding to manage a user's group membership.

將使用者新增至群組Add user to a group

下列範例會將使用者新增至群組。The following example adds a user to a group.

[FunctionName("addToGroup")]
public static Task AddToGroup(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
    ClaimsPrincipal claimsPrincipal,
    [SignalR(HubName = "chat")]
        IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
    var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
    return signalRGroupActions.AddAsync(
        new SignalRGroupAction
        {
            UserId = userIdClaim.Value,
            GroupName = "myGroup",
            Action = GroupAction.Add
        });
}

從群組中移除使用者Remove user from a group

下列範例會從群組中移除使用者。The following example removes a user from a group.

[FunctionName("removeFromGroup")]
public static Task RemoveFromGroup(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
    ClaimsPrincipal claimsPrincipal,
    [SignalR(HubName = "chat")]
        IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
    var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
    return signalRGroupActions.AddAsync(
        new SignalRGroupAction
        {
            UserId = userIdClaim.Value,
            GroupName = "myGroup",
            Action = GroupAction.Remove
        });
}

注意

為了讓 ClaimsPrincipal 正確地系結,您必須已在 Azure Functions 中設定驗證設定。In order to get the ClaimsPrincipal correctly bound, you must have configured the authentication settings in Azure Functions.

組態Configuration

SignalRConnectionInfoSignalRConnectionInfo

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 SignalRConnectionInfo 屬性。The following table explains the binding configuration properties that you set in the function.json file and the SignalRConnectionInfo attribute.

function.json 屬性function.json property 屬性內容Attribute property 說明Description
typetype n/an/a 必須設為 signalRConnectionInfoMust be set to signalRConnectionInfo.
directiondirection n/an/a 必須設為 inMust be set to in.
namename n/an/a 函式程式碼中用於連線資訊物件的變數名稱。Variable name used in function code for connection info object.
hubNamehubName HubNameHubName 此值必須設為 SignalR 中樞 (針對該中樞產生連線資訊) 的名稱。This value must be set to the name of the SignalR hub for which the connection information is generated.
userIduserId UserIdUserId 選擇性:要在存取金鑰權杖中設定的使用者識別碼宣告值。Optional: The value of the user identifier claim to be set in the access key token.
connectionStringSettingconnectionStringSetting ConnectionStringSettingConnectionStringSetting 包含 SignalR Service 連接字串 (預設值為 "AzureSignalRConnectionString") 的應用程式設定名稱The name of the app setting that contains the SignalR Service connection string (defaults to "AzureSignalRConnectionString")

SignalRSignalR

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 SignalR 屬性。The following table explains the binding configuration properties that you set in the function.json file and the SignalR attribute.

function.json 屬性function.json property 屬性內容Attribute property 說明Description
typetype n/an/a 必須設為 signalRMust be set to signalR.
directiondirection n/an/a 必須設為 outMust be set to out.
namename n/an/a 函式程式碼中用於連線資訊物件的變數名稱。Variable name used in function code for connection info object.
hubNamehubName HubNameHubName 此值必須設為 SignalR 中樞 (針對該中樞產生連線資訊) 的名稱。This value must be set to the name of the SignalR hub for which the connection information is generated.
connectionStringSettingconnectionStringSetting ConnectionStringSettingConnectionStringSetting 包含 SignalR Service 連接字串 (預設值為 "AzureSignalRConnectionString") 的應用程式設定名稱The name of the app setting that contains the SignalR Service connection string (defaults to "AzureSignalRConnectionString")

當您要在本機開發時,應用程式設定會進入 local.settings.json 檔案When you're developing locally, app settings go into the local.settings.json file.

後續步驟Next steps