Skip to content

Commit

Permalink
Fix HubConnectionContext.UserIdentifier is null
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Y-Sindo committed Sep 28, 2022
1 parent 84f2d69 commit b41b6b5
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 2 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);
}
}
}
25 changes: 25 additions & 0 deletions test/Microsoft.Azure.SignalR.Tests/ServiceLifetimeManagerFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,31 @@ public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExiste
Assert.True(false);
}

[Fact]
public async void SetUserIdTest()
{
var connectionContext = new TestConnectionContext();
connectionContext.Features.Set<IServiceUserIdFeature>(new ServiceUserIdFeature("testUser"));

var hubConnectionContext = new HubConnectionContext(connectionContext, new(), NullLoggerFactory.Instance);
var serviceLifetimeManager = MockLifetimeManager(new TestServiceConnectionManager<TestHub>());
await serviceLifetimeManager.OnConnectedAsync(hubConnectionContext);

Assert.Equal("testUser", hubConnectionContext.UserIdentifier);
}

[Fact]
public async void DoNotSetUserIdWithoutFeatureTest()
{
var connectionContext = new TestConnectionContext();

var hubConnectionContext = new HubConnectionContext(connectionContext, new(), NullLoggerFactory.Instance);
var serviceLifetimeManager = MockLifetimeManager(new TestServiceConnectionManager<TestHub>());
await serviceLifetimeManager.OnConnectedAsync(hubConnectionContext);

Assert.Null(hubConnectionContext.UserIdentifier);
}

private HubLifetimeManager<TestHub> MockLifetimeManager(IServiceConnectionManager<TestHub> serviceConnectionManager, IClientConnectionManager clientConnectionManager = null, IBlazorDetector blazorDetector = null)
{
clientConnectionManager ??= new ClientConnectionManager();
Expand Down

0 comments on commit b41b6b5

Please sign in to comment.