我如何在 SignalR Hub 中应用 [Authorize],它在我的其他 API 控制器上工作但不在 SignalR Hub 中工作,我可以在 SignalR 请求中发送 JWT 令牌。 这是我的 SignalR Hub 的 C# 代码
namespace LC_ERP
{
public class UsersHub : Hub
{
private readonly Dictionary<string, bool> _userStatuses = new Dictionary<string, bool>();
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[UserSession]
public override async Task OnConnectedAsync()
{
// Get the user ID from the JWT token in the connection request
var userId = GetUserIdFromToken(Context);
// Set the user status to true (online)
_userStatuses[userId] = true;
// Notify all connected clients of the updated user status
await Clients.All.SendAsync("UserStatusUpdated", userId, true);
await base.OnConnectedAsync();
}
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[UserSession]
public override async Task OnDisconnectedAsync(Exception exception)
{
// Get the user ID from the JWT token in the connection request
var userId = GetUserIdFromToken(Context);
// Set the user status to false (offline)
_userStatuses[userId] = false;
// Notify all connected clients of the updated user status
await Clients.All.SendAsync("UserStatusUpdated", userId, false);
await base.OnDisconnectedAsync(exception);
}
private string GetUserIdFromToken(HubCallerContext context)
{
var token = context.GetHttpContext().Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
var jwtHandler = new JwtSecurityTokenHandler();
var jwtToken = jwtHandler.ReadJwtToken(token);
return jwtToken.Claims.FirstOrDefault(c => c.Type == "id")?.Value;
}
}
}
那是我添加标题的角度代码:
var token:any = jwtService.getJwtToken();
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${environment.apiURL}/users`, { accessTokenFactory: () => token})
.build();
//console.log(jwtService.getJwtToken())
this.hubConnection.on('UserStatusUpdated', (userId: string, isOnline: boolean) => {
this.userStatuses[userId] = isOnline;
});
this.hubConnection.start();
在 signalR 中,第一个问题是 [Authorize] 属性不起作用,第二个问题是我在这一行中得到 null:
var token = context.GetHttpContext().Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
当我尝试获取 Authorization 标头时,它返回 null。