Set Context.UserIdentifier to different claim

Viewed 232

By default, signalr sets Context.UserIdentifier from ClaimTypes.NameIdentifier in jwt token. But I want to set it to different claim from token, which is userId and not username, because when I send message to specific user I have his id available. Is there a way to do it?

1 Answers

Implement IUserIdProvider and register it.

public class CustomUserIdProvider : IUserIdProvider
{
    public virtual string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.FindFirst(yourClaimTypeHere)?.Value;
    }
}

services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
Related