Skip to content

Commit

Permalink
Fix HubConnectionContext.UserIdentifier is null when negotiation wi…
Browse files Browse the repository at this point in the history
…th Management SDK

When clients negotiatie with Management SDK and connect to SignalR server, IUserIdProvider might not work as the user Id is set directly in the Management SDK.

To make HubConnectionContext.UserIdentifier have the valid value in this case, we should set it before the server can access it. HubLifetimeManager{THub}.OnConnectedAsync(HubConnectionContext) is the only chance we can set the value. However, we cannot access the Constants.ClaimType.UserId as ASRS system claims're trimmed there. HubConnectionContext.Features is the place where we can store the user Id.

The following code is our injection point.
https://github.com/dotnet/aspnetcore/blob/v6.0.9/src/SignalR/server/Core/src/HubConnectionHandler.cs#L132-L141
  • Loading branch information
Y-Sindo committed Sep 28, 2022
1 parent 84f2d69 commit 5d7cc4d
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 21 deletions.
11 changes: 11 additions & 0 deletions src/Microsoft.Azure.SignalR/HubHost/ServiceLifetimeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ public ServiceLifetimeManager(
}
}

public override Task OnConnectedAsync(HubConnectionContext connection)
{
var userIdFeature = connection.Features.Get<IServiceUserIdFeature>();
if (userIdFeature != null)
{
connection.UserIdentifier = userIdFeature.UserId;
connection.Features.Set<IServiceUserIdFeature>(null);
}
return base.OnConnectedAsync(connection);
}

public override async Task SendConnectionAsync(string connectionId, string methodName, object[] args, CancellationToken cancellationToken = default)
{
if (IsInvalidArgument(connectionId))
Expand Down
17 changes: 17 additions & 0 deletions src/Microsoft.Azure.SignalR/Internals/IServiceUserNameFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.AspNetCore.SignalR;

namespace Microsoft.Azure.SignalR
{
/// <summary>
/// When clients negotiate with Management SDK and connect to SignalR server, the <see cref="IUserIdProvider"/> might not work as the user Id is set directly in the Management SDK.
/// To make <see cref="HubConnectionContext.UserIdentifier"/> have the valid value in this case, we should set it before the server can access it. <see cref="HubLifetimeManager{THub}.OnConnectedAsync(HubConnectionContext)"/> is the only chance we can set the value. However, we cannot access the <see cref="Constants.ClaimType.UserId"/> as ASRS system claims're trimmed there. <see cref="HubConnectionContext.Features"/> is the place where we can store the user Id.
/// https://github.com/dotnet/aspnetcore/blob/v6.0.9/src/SignalR/server/Core/src/HubConnectionHandler.cs#L132-L141
/// </summary>
internal interface IServiceUserIdFeature
{
string UserId { get; }
}
}
15 changes: 15 additions & 0 deletions src/Microsoft.Azure.SignalR/Internals/ServiceUserIdFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Azure.SignalR
{
internal class ServiceUserIdFeature : IServiceUserIdFeature
{
public string UserId { get; }

public ServiceUserIdFeature(string userId)
{
UserId = userId;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public ClientConnectionContext(OpenConnectionMessage serviceMessage, Action<Http
HttpContext = BuildHttpContext(serviceMessage);
configureContext?.Invoke(HttpContext);

Features = BuildFeatures();
Features = BuildFeatures(serviceMessage);

if (serviceMessage.Headers.TryGetValue(Constants.AsrsMigrateFrom, out _))
{
Expand Down Expand Up @@ -234,7 +234,7 @@ public void CancelOutgoing(int millisecondsDelay = 0)
}
}

private FeatureCollection BuildFeatures()
private FeatureCollection BuildFeatures(OpenConnectionMessage serviceMessage)
{
var features = new FeatureCollection();
features.Set<IConnectionHeartbeatFeature>(this);
Expand All @@ -244,6 +244,12 @@ private FeatureCollection BuildFeatures()
features.Set<IConnectionTransportFeature>(this);
features.Set<IHttpContextFeature>(this);
features.Set<IConnectionStatFeature>(this);

var userIdClaim = serviceMessage.Claims.FirstOrDefault(c => c.Type == Constants.ClaimType.UserId);
if (userIdClaim != default)
{
features.Set<IServiceUserIdFeature>(new ServiceUserIdFeature(userIdClaim.Value));
}
return features;
}

Expand Down
30 changes: 30 additions & 0 deletions test/Microsoft.Azure.SignalR.Tests/ClientConnectionContextFacts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Security.Claims;
using Xunit;

namespace Microsoft.Azure.SignalR.Tests
{
public class ClientConnectionContextFacts
{
[Fact]
public void SetUserIdFeatureTest()
{
var claims = new Claim[] { new(Constants.ClaimType.UserId, "testUser") };
var connection = new ClientConnectionContext(new("connectionId", claims));
var feature = connection.Features.Get<IServiceUserIdFeature>();
Assert.NotNull(feature);
Assert.Equal("testUser", feature.UserId);
}

[Fact]
public void DoNotSetUserIdFeatureWithoutUserIdClaimTest()
{
var connection = new ClientConnectionContext(new("connectionId", Array.Empty<Claim>()));
var feature = connection.Features.Get<IServiceUserIdFeature>();
Assert.Null(feature);
}
}
}
38 changes: 19 additions & 19 deletions test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ namespace Microsoft.Azure.SignalR.Tests
{
public class ServiceLifetimeManagerFacts
{
private static readonly List<string> TestUsers = new List<string> {"user1", "user2"};
private static readonly List<string> TestUsers = new List<string> { "user1", "user2" };

private static readonly List<string> TestGroups = new List<string> {"group1", "group2"};
private static readonly List<string> TestGroups = new List<string> { "group1", "group2" };

private const string MockProtocol = "blazorpack";

private const string TestMethod = "TestMethod";

private static readonly object[] TestArgs = {"TestArgs"};
private static readonly object[] TestArgs = { "TestArgs" };

private static readonly List<string> TestConnectionIds = new List<string> {"connection1", "connection2"};
private static readonly List<string> TestConnectionIds = new List<string> { "connection1", "connection2" };

private static readonly IHubProtocolResolver HubProtocolResolver =
new DefaultHubProtocolResolver(new IHubProtocol[]
Expand Down Expand Up @@ -299,41 +299,41 @@ private static void VerifyServiceMessage(string methodName, ServiceMessage servi
switch (methodName)
{
case "SendAllAsync":
Assert.Null(((BroadcastDataMessage) serviceMessage).ExcludedList);
Assert.Null(((BroadcastDataMessage)serviceMessage).ExcludedList);
break;
case "SendAllExceptAsync":
Assert.Equal(TestConnectionIds, ((BroadcastDataMessage) serviceMessage).ExcludedList);
Assert.Equal(TestConnectionIds, ((BroadcastDataMessage)serviceMessage).ExcludedList);
break;
case "SendConnectionAsync":
Assert.Equal(TestConnectionIds[0], ((MultiConnectionDataMessage) serviceMessage).ConnectionList[0]);
Assert.Equal(TestConnectionIds[0], ((MultiConnectionDataMessage)serviceMessage).ConnectionList[0]);
break;
case "SendConnectionsAsync":
Assert.Equal(TestConnectionIds, ((MultiConnectionDataMessage) serviceMessage).ConnectionList);
Assert.Equal(TestConnectionIds, ((MultiConnectionDataMessage)serviceMessage).ConnectionList);
break;
case "SendGroupAsync":
Assert.Equal(TestGroups[0], ((GroupBroadcastDataMessage) serviceMessage).GroupName);
Assert.Null(((GroupBroadcastDataMessage) serviceMessage).ExcludedList);
Assert.Equal(TestGroups[0], ((GroupBroadcastDataMessage)serviceMessage).GroupName);
Assert.Null(((GroupBroadcastDataMessage)serviceMessage).ExcludedList);
break;
case "SendGroupsAsync":
Assert.Equal(TestGroups, ((MultiGroupBroadcastDataMessage) serviceMessage).GroupList);
Assert.Equal(TestGroups, ((MultiGroupBroadcastDataMessage)serviceMessage).GroupList);
break;
case "SendGroupExceptAsync":
Assert.Equal(TestGroups[0], ((GroupBroadcastDataMessage) serviceMessage).GroupName);
Assert.Equal(TestConnectionIds, ((GroupBroadcastDataMessage) serviceMessage).ExcludedList);
Assert.Equal(TestGroups[0], ((GroupBroadcastDataMessage)serviceMessage).GroupName);
Assert.Equal(TestConnectionIds, ((GroupBroadcastDataMessage)serviceMessage).ExcludedList);
break;
case "SendUserAsync":
Assert.Equal(TestUsers[0], ((UserDataMessage) serviceMessage).UserId);
Assert.Equal(TestUsers[0], ((UserDataMessage)serviceMessage).UserId);
break;
case "SendUsersAsync":
Assert.Equal(TestUsers, ((MultiUserDataMessage) serviceMessage).UserList);
Assert.Equal(TestUsers, ((MultiUserDataMessage)serviceMessage).UserList);
break;
case "AddToGroupAsync":
Assert.Equal(TestConnectionIds[0], ((JoinGroupWithAckMessage) serviceMessage).ConnectionId);
Assert.Equal(TestGroups[0], ((JoinGroupWithAckMessage) serviceMessage).GroupName);
Assert.Equal(TestConnectionIds[0], ((JoinGroupWithAckMessage)serviceMessage).ConnectionId);
Assert.Equal(TestGroups[0], ((JoinGroupWithAckMessage)serviceMessage).GroupName);
break;
case "RemoveFromGroupAsync":
Assert.Equal(TestConnectionIds[0], ((LeaveGroupWithAckMessage) serviceMessage).ConnectionId);
Assert.Equal(TestGroups[0], ((LeaveGroupWithAckMessage) serviceMessage).GroupName);
Assert.Equal(TestConnectionIds[0], ((LeaveGroupWithAckMessage)serviceMessage).ConnectionId);
Assert.Equal(TestGroups[0], ((LeaveGroupWithAckMessage)serviceMessage).GroupName);
break;
default:
break;
Expand Down

0 comments on commit 5d7cc4d

Please sign in to comment.