signalr - 保护 SignalR 调用

标签 signalr

我正在使用 SignalR Javascript 客户端和 ASP.NET ServiceHost。我需要 SignalR 集线器和回调只能被登录用户访问。我还需要能够使用来自 HttpContext.Current.User 的 FormsIdentity 从集线器获取当前登录用户的身份。

  • 如何保护集线器,以便只有经过身份验证的用户才能使用 SignalR?
  • 如何从 Hub 获取当前登录用户的身份?
  • 最佳答案

    您应该使用 this.Context.User.Identity可从 Hub 获得。 See a related question

    编辑:要停止未经身份验证的用户:

    public void ThisMethodRequiresAuthentication()
    {
      if(!this.Context.User.Identity.IsAuthenticated)
      {
        // possible send a message back to the client (and show the result to the user)
        this.Clients.SendUnauthenticatedMessage("You don't have the correct permissions for this action.");
        return;
      }
    
      // user is authenticated continue
    }
    

    编辑#2:
    这可能会更好,只需返回一条消息
     public string ThisMethodRequiresAuthentication()
        {
          if(!this.Context.User.Identity.IsAuthenticated)
          {
            // possible send a message back to the client (and show the result to the user)
            return "You don't have the correct permissions for this action.");
    
           // EDIT: or throw the 403 exception (like in the answer from Jared Kells (+1 from me for his answer), which I actually like better than the string)
           throw new HttpException(403, "Forbidden");
          }
    
          // user is authenticated continue
    
          return "success";
        }
    

    关于signalr - 保护 SignalR 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9991035/

    相关文章:

    c# - 从回调调用时,ASP.NET Core SignalR 客户端对象处理异常

    javascript - SignalR Asp.NET MVC5 用户信息

    c# - Asp.NET MVC/Web API 的模式满足 SignalR/Websockets

    xamarin.forms - Microsoft.AspNetCore.SignalR.Protocol.JsonHubProtocol' 抛出异常

    c# - 如何使用 C# 中的一个函数将 SqlDependency 和 SignalR 与 2 个不同的数据库一起使用?

    javascript - SignalR 无法在 Chrome 上使用 WebSocket 连接到服务器

    javascript - 信号客户端的 npm 包未连接

    c# - SignalR:加载集线器时出错

    c# - Signalr net client On 事件泛型类型参数

    c# - 关于在控制台应用程序中托管 SignalR