ASP NET Core SignalR OnDisconnectedAsync not firing with hub [Authorized]

Viewed 3240

.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?

3 Answers

If you have a debugger attached and close the client by closing the browser tab, then you'll never observe OnDisconnectedAsync being fired. This is because SignalR check if a debugger is attached and don't trigger certain timeouts in order to making debugging easier. If you close by calling stop on the client then you should see OnDisconnectedAsync called.

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

for blazor implement this code

@implements IAsyncDisposable

and paste this func. to code

public async ValueTask DisposeAsync()
{
    if (hubConnection is not null)
    {
        await hubConnection.DisposeAsync();
    }
}
Related