无法验证 SignalR 聊天中心

问题描述 投票:0回答:1

我正在使用 .NET core 8 Web api、signalr 和 Angular 制作一个实时聊天应用程序。我使用 .NET core 8 中引入的新身份验证系统和令牌身份验证。 我已经从角度前端实现了身份验证,它工作正常,并且我访问了授权方法。 但是,当我尝试对我的聊天中心进行身份验证时,它不会将其识别为经过身份验证的用户。 另外 Context.User?.Identity?.IsAuthenticated 这也是错误的。但 onConnectedAsync 函数被装饰为授权并且它可以工作。

这是我构建连接的前端聊天服务构造函数。

this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(`${this.baseUrl}/chathub`, {
        accessTokenFactory: () => this.authService.getToken()
      })
      .build();

我检查了网络选项卡。访问令牌随请求一起发送。

这是我的聊天中心。

[Authorize]
public override async Task OnConnectedAsync()
{

    var userId = Context.UserIdentifier; // Get user ID from authentication
    await Clients.All.SendAsync("ReceiveSystemMessage", $"{userId} joined.");
    await base.OnConnectedAsync();
}

[Authorize]
public override async Task OnDisconnectedAsync(Exception exception)
{

    var userId = Context.UserIdentifier; // Get user ID from authentication
    await Clients.All.SendAsync("ReceiveSystemMessage", $"{userId} left.");
    await base.OnDisconnectedAsync(exception);
}

连接成功并发送消息。但系统消息只显示“已加入”,没有id。

这是程序.cs

// Add Authentication
builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();
builder.Services.AddIdentityCore<User>()
    .AddEntityFrameworkStores<Context>()
    .AddApiEndpoints();

var app = builder.Build();

app.UseCors();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapIdentityApi<User>();

app.MapControllers();

app.MapHub<ChatHub>("/chathub");

app.Run();
c# .net angular signalr
1个回答
0
投票

您似乎已经在 SignalR 身份验证设置方面做了很多正确的事情。但是,如果 Context.User?.Identity?.IsAuthenticated 返回 false,则表明服务器未正确识别该令牌。您可以采取以下几个步骤来排查和解决此问题:

  1. 检查令牌有效性:确保客户端发送的令牌有效且未过期。您可以在服务器上解码令牌以验证其内容。
  2. 检查令牌接收:在服务器端,检查令牌是否被正确接收。您可能想要记录标头以查看授权标头是否存在且格式正确。
  3. 中间件顺序:中间件的顺序在 ASP.NET Core 中至关重要。确保 app.UseAuthentication();在 app.UseAuthorization(); 之前调用和之前 app.MapHub("/chathub");.
  4. SignalR Hub 授权:确保在您的 hub 方法上正确使用 [Authorize] 属性。如果您有自定义授权要求,请确保满足这些要求。
  5. 令牌配置:验证服务器和客户端上的令牌配置是否匹配,包括签名密钥和任何其他相关参数。
  6. HubConnectionContext:如果您使用自定义策略或角色,请确保它们已正确定义,并且用户的身份具有通过授权所需的声明。
  7. 调试:使用调试工具逐步完成身份验证过程并确定故障发生的位置。

通过执行这些步骤,您应该能够查明 SignalR 身份验证的问题。请记住,由于身份验证问题的安全敏感性,调试起来可能很棘手,因此请花点时间仔细检查身份验证流程的每个部分。

© www.soinside.com 2019 - 2024. All rights reserved.