I'm working on a chat application on the web using blazor web assemblly
I'm tring to push the states(Online / Offline) of users to each others.
here is the signalRHub
On connected is working fine.
public override Task OnConnectedAsync()
My problem is that OnDisconnectedAsync() not getting hitted by the debuger at all
Even after I close the client(browser) that the server is connected with.
public override Task OnDisconnectedAsync(Exception? exception)
{
var userId = _userManager.GetUserId(Context.User);
return base.OnDisconnectedAsync(exception);
}
CodePudding user response:
You need to configure the middleware for the token on the server for signalr.
services.AddAuthentication().AddIdentityServerJwt();
services.TryAddEnumerable(
ServiceDescriptor.Singleton
<IPostConfigureOptions<JwtBearerOptions>,ConfigureJwtBearerOptions>());
public class ConfigureJwtBearerOptions : IPostConfigureOptions<JwtBearerOptions>
{
public void PostConfigure(string name, JwtBearerOptions options)
{
var originalOnMessageReceived = options.Events.OnMessageReceived;
options.Events.OnMessageReceived = async context =>
{
await originalOnMessageReceived(context);
if (string.IsNullOrEmpty(context.Token))
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
path.StartsWithSegments("/hubs"))
{
context.Token = accessToken;
}
}
};
}
}
NOTE: This assumes your hub endpoint(s) start with "/hubs"