Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix HubConnectionContext.UserIdentifier is null when negotiation with Management SDK #1691

Merged
merged 3 commits into from
Sep 29, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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<ServiceUserIdFeature>();
if (userIdFeature != null)
{
connection.UserIdentifier = userIdFeature.UserId;
connection.Features.Set<ServiceUserIdFeature>(null);
}
return base.OnConnectedAsync(connection);
}

public override async Task SendConnectionAsync(string connectionId, string methodName, object[] args, CancellationToken cancellationToken = default)
{
if (IsInvalidArgument(connectionId))
Expand Down
22 changes: 22 additions & 0 deletions src/Microsoft.Azure.SignalR/Internals/ServiceUserIdFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// 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 class ServiceUserIdFeature
{
public string UserId { get; }

public ServiceUserIdFeature(string userId)
{
UserId = userId;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,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 @@ -237,7 +237,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 @@ -247,6 +247,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(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<ServiceUserIdFeature>();
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<ServiceUserIdFeature>();
Assert.Null(feature);
}
}
}
26 changes: 26 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,32 @@ public async void TestSendConnectionAsyncisOverwrittenWhenClientConnectionExiste
Assert.True(false);
}

[Fact]
public async void SetUserIdTest()
{
var connectionContext = new TestConnectionContext();
connectionContext.Features.Set(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);
Assert.Null(hubConnectionContext.Features.Get<ServiceUserIdFeature>());
}

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