【问题标题】:SingalR authorized user doesn't get message back ASP.Core 3.1SignalR 授权用户没有收到消息 ASP.Core 3.1
【发布时间】:2020-10-07 06:16:20
【问题描述】:

我正在尝试将身份用户与 SingalR 集成。至此,就连接到集线器,授权成功。 问题是我可以让它与组一起工作,但尽管授权工作,我不能直接由用户发送。我也尝试了电子邮件而不是用户唯一标识符,但结果是一样的。会喜欢你的意见。 谢谢。

智威汤逊:

 options.Events = new JwtBearerEvents
 {
      OnMessageReceived = context =>
      {
          var accessToken = context.Request.Query["access_token"];

          if (!string.IsNullOrEmpty(accessToken) &&(context.Request.Path.StartsWithSegments("/feed/get")))
          {
              context.Token = context.Request.Query["access_token"];
          }
          return Task.CompletedTask;
      }
 };

Startup.cs

 app.UseEndpoints(route =>
 {
     route.MapHub<ActivityHub>("/feed/Get");                
 });

集线器

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

public class ActivityHub : Hub
{     
    IAuthService AuthService;
    public ActivityHub(IAuthService authService)
    {
        AuthService = authService;
    }

    public override async Task OnConnectedAsync()
    {

        var user = await AuthService.GetUserByNameAsync(Context.User.Identity.Name);           

        await Clients.User(user.Id).SendAsync("receiveMessage", "Hello user"); //this doesn't get recived on client

        await Groups.AddToGroupAsync(Context.ConnectionId, user.Id);
        await Clients.Group(user.Id).SendAsync("receiveMessage", "Hello group!");//this works

        await base.OnConnectedAsync();

    }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
        }
    }
}

【问题讨论】:

  • 我建议使用组方法,在连接时将用户添加到组中,即使您创建单个用户组,Microsoft 实际上也建议这样做。如果你不想这样,那么我希望有人能帮助你解决你的问题。
  • 谢谢,我想我会这样做的。

标签: c# asp.net-core .net-core signalr


【解决方案1】:

正如我在 cmets 部分所说,最好的方法是使用组来归档您的目标。只需在连接方法上的单个用户组中添加一个用户。

正如您在 documentation 上看到的,在 SignalR 中使用单个用户组很常见。

【讨论】:

    【解决方案2】:

    如果您想自定义用户标识符,您可以实现自己的 IUserIdProvider,如文档https://docs.microsoft.com/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#use-claims-to-customize-identity-handling 中所示

    此外,在使用 Clients.User(...) 时,您应该使用 Context.UserIdentifier 来获取用户 ID,因为 SignalR 将使用它来区分用户。

    【讨论】:

    • 我看过文档,它们非常简短,我无法在网上找到很多示例。我想我会使用组来代替。
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多