Search code examples
asp.net-mvcsignalrasp.net-identitysignalr-2

How to securely send a message to a specific user


I am using ASP.NET MVC 5 and SignalR. I want to send a message to a specific user. I have followed the method which is explained in this tutorial (also suggested by this answer).

I have overridden IUserIdProvider, to use UserId as connectionId.

public class SignalRUserIdProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
        // use: UserId as connectionId
        return Convert.ToString(request.User.Identity.GetUserId<int>());
    }
}

And I have made the change to my app Startup to use the above custom provider:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var idProvider = new SignalRUserIdProvider();
        GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
        ConfigureAuth(app);
        app.MapSignalR();
    }
}

Now my client can pass destination ClientID to the hub, and hub will forward the message only to the requested Client, this is my Hub:

[Authorize] 
public class ChatHub : Hub
{
    public void Send(string message, string destClientId)
    {
        Clients.User(destClientId).messageReceived(Context.User.Identity.Name + " says: " + message);
    }
}

This is working perfectly fine. My question is about security and if this is the right approach for a secure website?

According to Introduction to SignalR Security, randomly generated connection id is part of SignalR security:

The server does not process any request from a connection id that does not match the user name. It is unlikely a malicious user could guess a valid request because the malicious user would have to know the user name and the current randomly-generated connection id.

The above approach is replacing the randomly selected connectionId with a fixed UserId... Is there any security issue with the above code?


Note: I am working on an e-commerce website where users need to be able to receive messages even if they are offline (the messages would be stored in DB and they can read once the are online).


Solution

  • You're pretty well on your way to the right solution. The only trick is that your security should be set up such that you can't spoof someone else's UserId.

    For instance, we have exactly the same scenario with SignalR, but we use the UserId claim from a JWT Token to tell who you are. So you would need to know the guy's login credentials if you wanted to receive his messages. You can't just change the UserId in the claims, because then the JWT signature would be invalid and you wouldn't be authenticated or authorized anymore.

    So TL;DR: use JWT authentication or something with a one-way signature that prevents tampering with the UserId.