Home > other >  Client IP Listing and Blocking in SignalR
Client IP Listing and Blocking in SignalR

Time:01-16

In Asp.net (core) .net 5, on the SignalR side, how can we list (receive) client IPs and block or allow certain IP's connections and requests by IP?

In my research, I saw that only Azure SingalR was mentioned.

How can we tell SignalR Hub to request Client IPs and accept (whitelist) or block (blacklist) public connection requests from specific IPs by coding in the application?

Is it possible ?

CodePudding user response:

In SignalR you can get the ip of the user with the HttpContext.

public class AppHub : Hub
{
    public string Ip => Context.GetHttpContext().Connection.RemoteIpAddress.ToString();

    public override async Task OnConnectedAsync()
    {
        if (Ip == "::1")
        {
            await Clients.All.SendAsync("ReceiveMessage", "Server", "Welcome to the server!");
        }
        else
        {
            throw new Exception("You are not allowed to connect to this server!");
        }

        await base.OnConnectedAsync();
    }
}

Another solution would be to create a hub filter wich you can find the documentation here : https://docs.microsoft.com/en-us/aspnet/core/signalr/hub-filters?view=aspnetcore-6.0

  •  Tags:  
  • Related