AbpSession.UserId null in SignalR Hub
See original GitHub issueAbp Package Version: Latest (Creating new template from site) Base Framework: .Net Core Steps need to reproduce: I have created a repo on GitHub that has a project to test. https://github.com/chadsmith12/SignalRTest/tree/master
But essentially when connecting to SignalR the following way:
new signalR.HubConnectionBuilder()
.withUrl(abp.appPath + 'signalr-TestHub', {
transport: signalR.HttpTransportType.LongPolling,
accessTokenFactory: () => {
return 'CURRENT JWT TOKEN HERE';
}
}).build();
And using the example Hub from the documentation like so:
[AbpMvcAuthorize]
public class TestHub : Hub, ITransientDependency
{
public IAbpSession AbpSession { get; set; }
public ILogger Logger { get; set; }
public TestHub()
{
AbpSession = NullAbpSession.Instance;
Logger = NullLogger.Instance;
}
public async Task SendMessage(string message)
{
var userId = AbpSession.UserId;
var connection = Context.User.Identity.GetUserId();
await Clients.All.SendAsync("getMessage", string.Format("User {0}: {1}", userId, message));
}
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
Debug.WriteLine("UserId" + AbpSession.UserId);
Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId);
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId);
}
}
And then connecting to a Hub that has the [AbpMvcAuthorize]
attribute over the Hub. You will be authorized correctly but at random times the UserId
inside of AbpSession
will be null, even though Context.User.Identity.GetUserId();
will give you the correct UserId. You can look at the logs for SignalR and notice that JWT is being sent correctly it seems each time and you will always get authorized when sending the JWT, but it is just that the AbpSession
is empty at random times.
I also had a stackoverflow post a couple days ago that describes it. https://stackoverflow.com/questions/53125573/aspnetboilerplate-signalr-jwt-authentication/
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:7 (5 by maintainers)
Top GitHub Comments
Hi. This problem occurs when using LongPolling. The signalr caches the first request context. For later requests, if you are lucky enough to run in the HTTP request context, it may work. Abp uses IHttpContextAccessor to get information from the current request context. In signalr it depends on luck. 😂
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/e0ded5d8702f389aa1f5947d3446f16aec845287/src/Abp.AspNetCore/AspNetCore/Runtime/Session/AspNetCorePrincipalAccessor.cs#L11
So currently you can use other connection modes,If there are other solutions, I will continue to comment.
Because mailiming’s solution didn’t work for me, I create another question https://github.com/aspnetboilerplate/aspnetboilerplate/issues/5314