Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR authentication within a Controller?

I'm playing with SignalR, and I can't seem to grasp authentication to build a demo app for public vs secure chat. There is one chat room, and I want to demonstrate that authenticated users will receive public messages and authenticated user messages. Authentication is done using the stock MVC(3) Internet app in AccountController.

Getting a Hub context within the controller doesn't make sense, since it doesn't have the connection id. How can I get the connection id to add the specific connection to a group for 'secure chat?' Should it be done in the controller? Or am I missing some way to do it within the hub?

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

            var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
            // add to signalr secure group
            // but no connection id here
like image 689
David Fox Avatar asked Dec 20 '22 13:12

David Fox


1 Answers

I was completely overlooking the obvious and well documented. Once the user is authenticated as normal, the Hub-derived class will be able to confirm authentication e.g.

public class Chat : Hub
{
    public void send(string message)
    {
        Clients.addMessage(message);
    }

    public void securesend(string message)
    {
        if (this.Context.User.Identity.IsAuthenticated)
        {
            // might not yet be a part of the "secured" group
            Groups.Add(this.Context.ConnectionId, "secured");
            Clients["secured"].addMessage("[SECURED] " + message);
        }
    }
}
like image 188
David Fox Avatar answered Jan 08 '23 09:01

David Fox