(this is so late :D but maybe useful for someone)
you can add accessTokenFactory to hubConnection in client side, and then check it in your backend(asp.net core 3.1).
from BackEnd you must override JwtBearerEvents and check access_token inside OnMessageReceived, also your hub endpoint path
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
// other options here ... //
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/ConnectionHub"))) // for me my hub endpoint is ConnectionHub
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
from client side, add your accessToken options (TypeScript):
public async startConnection(): Promise<void> {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:5001/ConnectionHub', { // ConnectionHub is hub endpoint
accessTokenFactory: () => this.getAccessToken(),
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
}).build();
await this.hubConnection.start();
// ....
}
getAccessToken(): string {
return 'your token' ; }
microsoft said:
Individual hub methods can have the [Authorize] attribute applied as well
[Authorize]
public class ChatHub : Hub
{
public async Task Send(string message)
{
// ... send a message to all users ...
}
[Authorize("Administrators")]
public void BanUser(string userName)
{
// ... ban a user from the chat room (something only Administrators can do) ...
}
}
and finaly you can read and check claims or identity attributes inside any of hub's method:
public override async Task OnConnectedAsync()
{
// Get UserID. Assumed the user is logged before connecting to chat and userid is saved in session.
string userID = Context.User.Identity.Name;
// Get ChatHistory and call the client function. See below
await GetHistoryAsync(userID);
await base.OnConnectedAsync();
}