Search code examples
signalraspnetboilerplateasp.net-core-signalr

aspnetboilerplate: SignalR JWT Authentication


We are trying to integrate SignalR in an 3rd party application to talk to our Hubs we have for our aspnetboilerplate application. This is using the .NET Core template. We are having an issue with the session in aspnetboilerplate having a null UserId even when getting past the attribute on our Hub to check for authorization.

The issue we are having is at random times the UserId inside of AbpSession will just be null. It gets past the [Authorize] attribute but aspnetboilerplate seems to think the UserId is null at random times. I can invoke a method on our Hub and see the UserId is correct for that user. Then the very next time I invoke that same method on the hub with the same user the UserId inside of AbpSession is null. I can then invoke the method again and the UserId will sometimes be null or sometimes be correct. Their doesn't seem to be any consistency in this issue. Every now and then it will alternate between being null and having the correct UserId.

Our client code:

let connection = new signalR.HubConnectionBuilder()
.withUrl('ENTER HUB URL HERE',
{
  transport: signalR.HttpTransportType.LongPolling,
  accessTokenFactory: () => {
    return 'BEARER TOKEN HERE'
 }}).build()

 connection.invoke('sendGroupMessage', text, hardCodedChatGroup)

Here is a sample of our SignalR Hub on the server:

    [AbpMvcAuthorize]
public class OpenChatHub : Hub, ITransientDependency
{
    public IAbpSession AbpSession { get; set; }

    public ILogger Logger { get; set; }

    public OpenChatHub()
    {
        AbpSession = NullAbpSession.Instance;
        Logger = NullLogger.Instance;
    }

    public async Task SendGroupMessage(string message, string groupName)
    {
        // logic for the SendGroupMessage would be here
        var msg = new
        {
            sendById = AbpSession.UserId, // this will be null at random times
            message = message
        };
        await Clients.Group(group).SendAsync("receiveChatMessage", msg);
    }
}

I can view the requests for SignalR negotiating and communicating with the Hub and I can see the token being passed correctly each time.


Solution

  • After doing a bit more research on this while trying to get a test project together that I could put on GitHub to reproduce the issue I did end up solving the issue.

    Using the following inside of our Hub gives us the correct UserId each time now. Context.User.Identity.GetUserId();

    I believe this must be a bug inside of aspnetboilerplate now. I will be trying to get an issue reported on the GitHub.