With Azure SignalR Service, that mapping is taken care of by the service itself. You would just need to use the userId itself (which could map to multiple connections, one per connected client) and/or groupName as applicable.
The userId itself can be any string like a username or email ID. And the same goes for 'groupName'.
As an example, to work with groups, you would essentially need 3 functions like this
// Will be called by users themselves to connect to Azure SignalR directly.
//
// Example assumes Easy Auth is used
[FunctionName("Negotiate")]
public static SignalRConnectionInfo Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "negotiate")] HttpRequest req,
[SignalRConnectionInfo(HubName = "chat", UserId = "{headers.x-ms-client-principal-id}")]SignalRConnectionInfo connectionInfo,
ILogger log)
{
return connectionInfo;
}
// Used by a group admin or the user themselves to join a group
//
// Example assumes both groupName and userId are passed
[FunctionName("AddToGroup")]
public static Task AddToGroup(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "{groupName}/add/{userId}")]HttpRequest req,
string groupName,
string userId,
[SignalR(HubName = "chat")]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
return signalRGroupActions.AddAsync(
new SignalRGroupAction
{
UserId = userId,
GroupName = groupName,
Action = GroupAction.Add
});
}
// Used to send messages to a group. This would involve all users/devices
// added to the group using the previous function
//
// Example assumes both groupName and userId are passed
[FunctionName("SendMessageToGroup")]
public static Task SendMessage(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "{groupName}/send")]object message,
string groupName,
[SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
return signalRMessages.AddAsync(
new SignalRMessage
{
// the message will be sent to the group with this name
GroupName = groupName,
Target = "newMessage",
Arguments = new[] { message }
});
}
You can read more about the Azure SignalR Service Bindings for Azure Functions in the official docs.
If you would still want to keep track of connections, you can subscribe to events that the service publishes which return the connectionId along with the userId of the client who connected/disconnected from the service.
The SignalRMessage and SignalRGroupAction classes support both connectionId and userId to identify connections and users respectively.