0

I just managed to get my SignalR chat going, and I ran into this problem.

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var chat = $.connection.chatHub;
        // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (name, message) {

            $('#chat-body').append('<li><strong>' + name + ' :</strong> ' + message);

        };

        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#send-chat-msg-btn').click(function () {

                // Call the Send method on the hub.
                chat.server.send('Username', $('#message-input-field').val());

                // Clear text box and reset focus for next comment.
                $('#message-input-field').val('').focus();

            });
        });
    });
</script>

The username is set in this javascript code, when sending to the server.

I don't want that, as people can pretend to be other people by changing their name here.

public class ChatHub : Hub
{
    DatabaseContext db = new DatabaseContext();

    public void Send(string name, string message)
    {
        // Get character
        string Username = User.Identity.GetUserName();
        Character Character = db.Characters.Where(c => c.Name == Username).FirstOrDefault();

        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }
}

The name is sent to this ChatHub
But I want the name to be set here instead of the JS code.
But I am not able to get the name from the database cause it says User does not exist in the current context

How can I set the name here in the model, instead of in the js code?

Thank you.

Petter Petter
  • 93
  • 1
  • 8

1 Answers1

1

Normally in MVC, if you're not in a controller you want to use HttpContext.Current.User.Identity. That won't work correctly for hubs though - if you think about it, the hub has a ton of connections and doesn't necessarily run under a particular user's HTTP context. Instead, you should use the User property on HubCallerContext.

Note this will only be populated if your hub is configured to use authentication - otherwise the server has no way to know the client's user name. See here. If you're self-hosting using OWIN you'll need to configre the auth module before calling MapSignalR (see this answer).

Community
  • 1
  • 1
Tim Copenhaver
  • 3,282
  • 13
  • 18