Asp.net-core – UserId in SignalR Core

asp.net-coreasp.net-core-signalr

I'm using SignalR with ASP.NET Core 2.0 and I'm trying to send a notification for a specific user like this:

_notification.Clients.User(id).InvokeAsync("SendMes");

where _notification is IHubContext.
But it doesn't work. When I send the notification for all users, everything is fine and all users get the notification. But when I send it to a specific user, nothing happens. In connections I have needed user but it seems as if he doesn't have userId. So how can I do this? By access to Identity and claims? If so, how to do this?

Best Answer

I was facing a similar problem and the following article helped me figure it out: https://docs.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-2.1

In the Hub (server-side), I checked Context.UserIdentifier and it was null, even though the user was authenticated. It turns out that SignalR relies on ClaimTypes.NameIdentifier and I was only setting ClaimTypes.Name. So, basically I added another claim and it worked out (Context.UserIdentifier is set correctly after that).

Below, I share part of the authentication code I have, just in case it helps:

var claims = userRoles.Split(',', ';').Select(p => new Claim(ClaimTypes.Role, p.Trim())).ToList();
claims.Insert(0, new Claim(ClaimTypes.Name, userName));
claims.Insert(1, new Claim(ClaimTypes.NameIdentifier, userName)); // this is the claim type that is used by SignalR
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);

Be careful, SignalR users and groups are case-sensitive.

Related Topic