SignalR authentication within a Controller?

2019-03-31 12:18发布

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

2条回答
小情绪 Triste *
2楼-- · 2019-03-31 12:52

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);
        }
    }
}
查看更多
Anthone
3楼-- · 2019-03-31 13:11

Make sure you take a look at the latest version of SignalR as we have nice built in Attributes you can use for authorization now.

http://weblogs.asp.net/davidfowler/archive/2012/11/11/microsoft-asp-net-signalr.aspx

查看更多
登录 后发表回答