Skip to content

Commit b41b6b5

Browse files
committed
Fix HubConnectionContext.UserIdentifier is null
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 84f2d69 commit b41b6b5

File tree

6 files changed

+106
-2
lines changed

6 files changed

+106
-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<IServiceUserIdFeature>();
57+
if (userIdFeature != null)
58+
{
59+
connection.UserIdentifier = userIdFeature.UserId;
60+
connection.Features.Set<IServiceUserIdFeature>(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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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 interface IServiceUserIdFeature
14+
{
15+
string UserId { get; }
16+
}
17+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
namespace Microsoft.Azure.SignalR
5+
{
6+
internal class ServiceUserIdFeature : IServiceUserIdFeature
7+
{
8+
public string UserId { get; }
9+
10+
public ServiceUserIdFeature(string userId)
11+
{
12+
UserId = userId;
13+
}
14+
}
15+
}

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

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

134-
Features = BuildFeatures();
134+
Features = BuildFeatures(serviceMessage);
135135

136136
if (serviceMessage.Headers.TryGetValue(Constants.AsrsMigrateFrom, out _))
137137
{
@@ -234,7 +234,7 @@ public void CancelOutgoing(int millisecondsDelay = 0)
234234
}
235235
}
236236

237-
private FeatureCollection BuildFeatures()
237+
private FeatureCollection BuildFeatures(OpenConnectionMessage serviceMessage)
238238
{
239239
var features = new FeatureCollection();
240240
features.Set<IConnectionHeartbeatFeature>(this);
@@ -244,6 +244,12 @@ private FeatureCollection BuildFeatures()
244244
features.Set<IConnectionTransportFeature>(this);
245245
features.Set<IHttpContextFeature>(this);
246246
features.Set<IConnectionStatFeature>(this);
247+
248+
var userIdClaim = serviceMessage.Claims.FirstOrDefault(c => c.Type == Constants.ClaimType.UserId);
249+
if (userIdClaim != default)
250+
{
251+
features.Set<IServiceUserIdFeature>(new ServiceUserIdFeature(userIdClaim.Value));
252+
}
247253
return features;
248254
}
249255

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<IServiceUserIdFeature>();
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<IServiceUserIdFeature>();
27+
Assert.Null(feature);
28+
}
29+
}
30+
}

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,31 @@ 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<IServiceUserIdFeature>(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+
}
252+
228253
private HubLifetimeManager<TestHub> MockLifetimeManager(IServiceConnectionManager<TestHub> serviceConnectionManager, IClientConnectionManager clientConnectionManager = null, IBlazorDetector blazorDetector = null)
229254
{
230255
clientConnectionManager ??= new ClientConnectionManager();

0 commit comments

Comments
 (0)