Skip to content

Commit 19bfa54

Browse files
authored
Fix HubConnectionContext.UserIdentifier is null when negotiation with Management SDK (#1691)
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 accesses 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 are trimmed there. HubConnectionContext.Features is the place where we can store the user Id. The following code is the injection point. https://github.com/dotnet/aspnetcore/blob/v6.0.9/src/SignalR/server/Core/src/HubConnectionHandler.cs#L132-L141 Fixes #1679
1 parent e99d04c commit 19bfa54

File tree

5 files changed

+97
-2
lines changed

5 files changed

+97
-2
lines changed

src/Microsoft.Azure.SignalR/HubHost/ServiceLifetimeManager.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,17 @@ public ServiceLifetimeManager(
5151
}
5252
}
5353

54+
public override Task OnConnectedAsync(HubConnectionContext connection)
55+
{
56+
var userIdFeature = connection.Features.Get<ServiceUserIdFeature>();
57+
if (userIdFeature != null)
58+
{
59+
connection.UserIdentifier = userIdFeature.UserId;
60+
connection.Features.Set<ServiceUserIdFeature>(null);
61+
}
62+
return base.OnConnectedAsync(connection);
63+
}
64+
5465
public override async Task SendConnectionAsync(string connectionId, string methodName, object[] args, CancellationToken cancellationToken = default)
5566
{
5667
if (IsInvalidArgument(connectionId))
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using Microsoft.AspNetCore.SignalR;
5+
6+
namespace Microsoft.Azure.SignalR
7+
{
8+
/// <summary>
9+
/// 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.
10+
/// 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.
11+
/// https://github.com/dotnet/aspnetcore/blob/v6.0.9/src/SignalR/server/Core/src/HubConnectionHandler.cs#L132-L141
12+
/// </summary>
13+
internal class ServiceUserIdFeature
14+
{
15+
public string UserId { get; }
16+
17+
public ServiceUserIdFeature(string userId)
18+
{
19+
UserId = userId;
20+
}
21+
}
22+
}

src/Microsoft.Azure.SignalR/ServerConnections/ClientConnectionContext.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ public ClientConnectionContext(OpenConnectionMessage serviceMessage, Action<Http
134134
HttpContext = BuildHttpContext(serviceMessage);
135135
configureContext?.Invoke(HttpContext);
136136

137-
Features = BuildFeatures();
137+
Features = BuildFeatures(serviceMessage);
138138

139139
if (serviceMessage.Headers.TryGetValue(Constants.AsrsMigrateFrom, out _))
140140
{
@@ -237,7 +237,7 @@ public void CancelOutgoing(int millisecondsDelay = 0)
237237
}
238238
}
239239

240-
private FeatureCollection BuildFeatures()
240+
private FeatureCollection BuildFeatures(OpenConnectionMessage serviceMessage)
241241
{
242242
var features = new FeatureCollection();
243243
features.Set<IConnectionHeartbeatFeature>(this);
@@ -247,6 +247,12 @@ private FeatureCollection BuildFeatures()
247247
features.Set<IConnectionTransportFeature>(this);
248248
features.Set<IHttpContextFeature>(this);
249249
features.Set<IConnectionStatFeature>(this);
250+
251+
var userIdClaim = serviceMessage.Claims?.FirstOrDefault(c => c.Type == Constants.ClaimType.UserId);
252+
if (userIdClaim != default)
253+
{
254+
features.Set(new ServiceUserIdFeature(userIdClaim.Value));
255+
}
250256
return features;
251257
}
252258

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using System;
5+
using System.Security.Claims;
6+
using Xunit;
7+
8+
namespace Microsoft.Azure.SignalR.Tests
9+
{
10+
public class ClientConnectionContextFacts
11+
{
12+
[Fact]
13+
public void SetUserIdFeatureTest()
14+
{
15+
var claims = new Claim[] { new(Constants.ClaimType.UserId, "testUser") };
16+
var connection = new ClientConnectionContext(new("connectionId", claims));
17+
var feature = connection.Features.Get<ServiceUserIdFeature>();
18+
Assert.NotNull(feature);
19+
Assert.Equal("testUser", feature.UserId);
20+
}
21+
22+
[Fact]
23+
public void DoNotSetUserIdFeatureWithoutUserIdClaimTest()
24+
{
25+
var connection = new ClientConnectionContext(new("connectionId", Array.Empty<Claim>()));
26+
var feature = connection.Features.Get<ServiceUserIdFeature>();
27+
Assert.Null(feature);
28+
}
29+
}
30+
}

test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,32 @@ public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExiste
225225
Assert.True(false);
226226
}
227227

228+
[Fact]
229+
public async void SetUserIdTest()
230+
{
231+
var connectionContext = new TestConnectionContext();
232+
connectionContext.Features.Set(new ServiceUserIdFeature("testUser"));
233+
234+
var hubConnectionContext = new HubConnectionContext(connectionContext, new(), NullLoggerFactory.Instance);
235+
var serviceLifetimeManager = MockLifetimeManager(new TestServiceConnectionManager<TestHub>());
236+
await serviceLifetimeManager.OnConnectedAsync(hubConnectionContext);
237+
238+
Assert.Equal("testUser", hubConnectionContext.UserIdentifier);
239+
}
240+
241+
[Fact]
242+
public async void DoNotSetUserIdWithoutFeatureTest()
243+
{
244+
var connectionContext = new TestConnectionContext();
245+
246+
var hubConnectionContext = new HubConnectionContext(connectionContext, new(), NullLoggerFactory.Instance);
247+
var serviceLifetimeManager = MockLifetimeManager(new TestServiceConnectionManager<TestHub>());
248+
await serviceLifetimeManager.OnConnectedAsync(hubConnectionContext);
249+
250+
Assert.Null(hubConnectionContext.UserIdentifier);
251+
Assert.Null(hubConnectionContext.Features.Get<ServiceUserIdFeature>());
252+
}
253+
228254
private HubLifetimeManager<TestHub> MockLifetimeManager(IServiceConnectionManager<TestHub> serviceConnectionManager, IClientConnectionManager clientConnectionManager = null, IBlazorDetector blazorDetector = null)
229255
{
230256
clientConnectionManager ??= new ClientConnectionManager();

0 commit comments

Comments
 (0)