如何获取使用带有 owin 身份验证的客户端 mvc 应用程序的 SignalR 连接用户的身份?

How to get identity of SignalR connected users which are using client mvc application with owin authentication?

在我的解决方案中,我有 2 个项目:SignalRServerWebClient,它们都是 MVC 应用程序. 在我的服务器中,我使用了 SignalR 2 Hub 并且在客户端项目中我使用了 jquery SignalR 库来连接到集线器服务器通过将托管服务器 url 作为集线器连接 url.

一切正常,客户端可以从服务器接收消息。

问题:在客户端项目中,我添加了身份验证,用户必须输入他们的用户名和密码才能查看将要查看哪些消息的页面。 现在我想获取已连接到 SignalR Hub Server 的登录用户名,并使用此用户名向每个用户发送相关消息。

在与服务器项目分离的客户端项目中进行身份验证时,我如何知道哪个用户已连接到服务器?

JQuery 客户中心:

var PbxHub = $.connection.pbxhub;

$.connection.hub.url = "http://localhost:10437/signalr";
$.connection.hub.logging = true;

$.connection.hub.start({
    jsonp: true,
    withCredentials: false
}).done(function () {
    console.log('Hub is connected.');
});

$.connection.hub.disconnected(function () {
    console.log('Hub is disconnected.');
    setTimeout(function () {
        $.connection.hub.start();
    }, 1500); // Restart connection after 1500 miliseconds.
});

客户端启动:

public void Configuration(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Home/Login"),
    });
}

服务器启动:

    public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            var hubConfiguration = new HubConfiguration
            {
                EnableJavaScriptProxies = true,
                EnableJSONP = true,
                EnableDetailedErrors = true
            };

            map.UseCors(CorsOptions.AllowAll);
            map.RunSignalR(hubConfiguration);
        });
    }

感谢任何想法。

如此处的 Microsoft 文档所述https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-3.1#cookie-authentication

In a browser-based app, cookie authentication allows your existing user credentials to automatically flow to SignalR connections. When using the browser client, no additional configuration is needed. If the user is logged in to your app, the SignalR connection automatically inherits this authentication.

因此,通过使用在客户端应用程序中使用的相同 DBContext,我可以访问连接到集线器的用户的 connectionId,并在向他们发送消息后将记录插入数据库。

    if (_context.Extension.Any(ex=>ex.Code.ToString() == deviceName))
    {
        extensionID = _context.Extension.SingleOrDefault(ex => ex.Code.ToString() == deviceName).ID.ToString();
    }
    else { return; }

    asterHub.Clients.User(extensionID).SendState(
            e.Device_state.Name,
            string.Format("{0}:{1}:{2}",
                pc.GetHour(DateTime.Now),
                pc.GetMinute(DateTime.Now),
                pc.GetSecond(DateTime.Now)),
            state,
            stateCode);