ASP NET Core SignalR OnDisconnectedAsync not firing with hub [Authorized]
.net core 2.1
Hub code:
[Authorize]
public class OnlineHub : Hub
{
public override async System.Threading.Tasks.Task OnConnectedAsync()
{
int userId = Context.UserIdentifier;
await base.OnConnectedAsync();
}
[AllowAnonymous]
public override async System.Threading.Tasks.Task OnDisconnectedAsync(Exception exception)
{
var b = Context.ConnectionId;
await base.OnDisconnectedAsync(exception);
}
Client code:
$(document).ready(() => {
let token = "token";
const connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:44343/online", { accessTokenFactory: () => token })
.configureLogging(signalR.LogLevel.Debug)
.build();
connection.start().catch(err => console.error(err.toString()));
});
Without [Authorize] all works fine, except Context.UserIdentifier in OnConnectedAsync, and it's explainable, but... with [Authorize] attribute on Hub class, OnConnectedAsync start working and OnDisconnected not fires at all, including 30sec timeout (by default).
Any ideas?
Add
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtAudience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
This should trigger OnDisconnectedAsync in SignalR Hub