简体   繁体   中英

SignalR how can I get access to claims from connected users?

In my application .net core I want to notify the user about some action made by other user. My SignalR connection is authorized so SignalR should have access to connected user claims, and he has. 在此处输入图像描述

In those claims users have IDs, so I was thinking maybe I can search somehow the user based on that Id, and will send the notification to particualr user, but I've no idea how can I find him in mHubContext, or maybe I should do it in any other way?

Maybe I should override OnConnected method and store theirs Id in some static hashset/dictionary?

You can use the following approach in order to access some properties user, connection, etc.

[HubName("demoHub")]
public class DemoHub : Hub
{
    public readonly static ConnectionMapping<string> connections = 
        new ConnectionMapping<string>();

    public override async Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        connections.Add(name, Context.ConnectionId);
        //await Groups.Add(Context.ConnectionId, Context.QueryString["group"]);
        await base.OnConnected();
    }

    public override async Task OnDisconnected(bool stopCalled)
    {
        string name = Context.User.Identity.Name;
        connections.Remove(name, Context.ConnectionId);
        //await Groups.Remove(Context.ConnectionId, Context.QueryString["group"]);
        await base.OnDisconnected(stopCalled);
    }

    public override async Task OnReconnected()
    {
        string name = Context.User.Identity.Name;
        if (!connections.GetConnections(name).Contains(Context.ConnectionId))
        {
            connections.Add(name, Context.ConnectionId);
            //await Groups.Add(Context.ConnectionId, Context.QueryString["group"]);
        }
        await base.OnReconnected();
    }
}

Update: If needed, you can use the following methods or create similar ones using the same logic:

public Task JoinToGroup(string groupName)
{
    return Groups.Add(Context.ConnectionId, groupName);
}

public Task LeaveFromGroup(string groupName)
{
    return Groups.Remove(Context.ConnectionId, groupName);
}

public async Task AddToGroup(string connectionId, string groupName)
{
    await Groups.Add(connectionId, groupName);
    //await Clients.Group(groupName).ReceiveMessage("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
}

public async Task RemoveFromGroup(string connectionId, string groupName)
{
    await Groups.Remove(connectionId, groupName);
    //await Clients.Group(groupName).ReceiveMessage("Send", $"{Context.ConnectionId} has left the group {groupName}.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM