If you use SignalR hubs and want to authorize methods in the same hub, you need to use the Authorize attribute on the hub. those.
[Authorize]
public class MessagingHub: Hub
{
public Task Send(string data)
{
return Clients.Caller.SendAsync("Send", "Data To Send");
}
}
Hub, , Send , :
[Authorize]
public class MessagingHub: Hub
{
public Task Send(string data)
{
var identity = (ClaimsIdentity)Context.User.Identity;
return Clients.Caller.SendAsync("Send", "Data To Send");
}
}
Json Web Tokens (JWT) , , , Hub Send.
NB. - Angular 6.
import { HubConnection } from "@aspnet/signalr";
import * as signalR from '@aspnet/signalr';
...
private _messagingHubConnection: HubConnection | undefined;
public async: any;
...
constructor(){}
...
SendMessg(): void {
if (this._messagingHubConnection) {
this._messagingHubConnection.invoke('Send');
}
}
...
ngOnInit(){
this._messagingHubConnection= new signalR.HubConnectionBuilder()
.withUrl("messaging", { accessTokenFactory: () => "jwt_token" }) //have a logic that gets the current user authentication token from the browser
.build();
this._messagingHubConnection.start().then(() => {
this.SendMessg();
}).catch(err => console.error(err.toString()));
if (this._messagingHubConnection) {
this._messagingHubConnection.on('Send', (data: any) => {
//data represents response/message received from Hub method'd return value.
});
}
}
NB. .Net Core 2.1, Hub. , signalR
.Net Core , StartUp.cs ;
services.AddSignalR();
app.UseWebSockets();
app.UseAuthentication();
app.UseSignalR(routes => {
routes.MapHub<LoopyHub>("/messaging");
});
NB. , GitHub SignalR, , , - - . .. .
, .NET Core & Angular; , , , .