Jwt令牌到期后如何断开SignalR Hub客户端

时间:2018-11-06 20:26:27

标签: c# asp.net-core signalr jwt

我一直在玩Microsoft的ChatHub示例,以获取有关新发布的网络核心signalR的一些知识。我实现了Jwt身份验证,并向我的Hub添加了Authorize。然后,我配置了Jwt身份验证以验证到期时间。但是,如果令牌有效时客户端成功连接到集线器。即使令牌过期,它仍保持连接。客户端无法将任何请求发布到同一服务器的其他端点,但是可以获取所有推送通知。您可以看到我的游乐场here

我的问题是:在Jwt令牌过期后,是否有任何解决方法来断开客户端连接?

2 个答案:

答案 0 :(得分:2)

您必须自己跟踪连接。

这是连接存储的示例,可以在您提供的代码中使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace SignalRServer.API.Hubs
{
  public class HubConnectionsStorage
  {
    private readonly Dictionary<string, HashSet<string>> _connectionsByJwtToken;
    private readonly Dictionary<string, string> _jwtTokenByConnection;
    private readonly Dictionary<string, HashSet<string>> _connectionsByGroup;
    private readonly Dictionary<string, HashSet<string>> _groupsByConnection;
    private readonly ReaderWriterLockSlim _lock;

    public HubConnectionsStorage()
    {
      _connectionsByJwtToken = new Dictionary<string, HashSet<string>>();
      _jwtTokenByConnection = new Dictionary<string, string>();
      _connectionsByGroup = new Dictionary<string, HashSet<string>>();
      _groupsByConnection = new Dictionary<string, HashSet<string>>();
      _lock = new ReaderWriterLockSlim();
    }

    public void AddConnection(string connectionId, string jwtToken)
    {
      _lock.EnterWriteLock();

      try
      {
        _jwtTokenByConnection[connectionId] = jwtToken;

        if (!_connectionsByJwtToken.TryGetValue(jwtToken, out var connections))
          _connectionsByJwtToken[jwtToken] = connections = new HashSet<string>();

        connections.Add(connectionId);
      }
      finally
      {
        _lock.ExitWriteLock();
      }
    }

    public void AddConnectionToGroup(string connectionId, string group)
    {
      _lock.EnterWriteLock();

      try
      {
        if(!_connectionsByGroup.TryGetValue(group, out var connections))
          _connectionsByGroup[group] = connections = new HashSet<string>();

        connections.Add(connectionId);

        if (!_groupsByConnection.TryGetValue(connectionId, out var groups))
          _groupsByConnection[connectionId] = groups = new HashSet<string>();

        groups.Add(group);

      }
      finally
      {
        _lock.ExitWriteLock();
      }
    }

    public void RemoveConnectionFromGroup(string connectionId, string group)
    {
      _lock.EnterWriteLock();

      try
      {
        if (!_connectionsByGroup.TryGetValue(group, out var connections))
          return;

        if(!connections.Remove(connectionId))
          return;

        if (connections.Count == 0)
          _connectionsByGroup.Remove(group);

        var groups = _groupsByConnection[connectionId];

        groups.Remove(group);

        if (groups.Count == 0)
          _groupsByConnection.Remove(connectionId);
      }
      finally
      {
        _lock.ExitWriteLock();
      }
    }

    public void RemoveConnection(string connectionId)
    {
      _lock.EnterWriteLock();

      try
      {
        if(!_jwtTokenByConnection.TryGetValue(connectionId, out var jwtToken))
          return;

        _jwtTokenByConnection.Remove(connectionId);

        var jwtConnections = _connectionsByJwtToken[jwtToken];

        jwtConnections.Remove(connectionId);

        if (jwtConnections.Count == 0)
          _connectionsByJwtToken.Remove(jwtToken);

        if(!_groupsByConnection.TryGetValue(connectionId, out var groups))
          return;

        foreach (var group in groups)
        {
          var connections = _connectionsByGroup[group];
          connections.Remove(connectionId);

          if (connections.Count == 0)
            _connectionsByGroup.Remove(group);
        }

        _groupsByConnection.Remove(connectionId);
      }
      finally
      {
        _lock.ExitWriteLock();
      }
    }

    public List<string> GetGroupConnections(string group)
    {
      _lock.EnterReadLock();

      try
      {
        if (_connectionsByGroup.TryGetValue(group, out var connections))
          return connections.ToList();

        return new List<string>();
      }
      finally 
      {
        _lock.ExitReadLock();
      }
    }

    public void RemoveExpiredConnections(Func<string, bool> validateJwtToken)
    {
      _lock.EnterWriteLock();

      try
      {
        foreach (var jwtToken in _connectionsByJwtToken.Keys.ToList())
        {
          var isValid = validateJwtToken(jwtToken);

          if (isValid) 
            continue;

          var invalidConnections = _connectionsByJwtToken[jwtToken];

          foreach (var invalidConnection in invalidConnections)
          {
            if (_groupsByConnection.TryGetValue(invalidConnection, out var connectionGroups))
            {
              foreach (var group in connectionGroups)
              {
                var groupConnections = _connectionsByGroup[@group];
                groupConnections.Remove(invalidConnection);

                if (groupConnections.Count == 0)
                  _connectionsByGroup.Remove(@group);
              }

              _groupsByConnection.Remove(invalidConnection);
            }

            _jwtTokenByConnection.Remove(invalidConnection);
          }

          _connectionsByJwtToken.Remove(jwtToken);
        }
      }
      finally 
      {
        _lock.ExitWriteLock();
      }
    }
  }
}

您可以将其作为单例传递到集线器

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using SignalRServer.API.Services;

namespace SignalRServer.API.Hubs
{
[Authorize]
public class NewsHub : Hub
{
private readonly NewsService newsService;
private readonly HubConnectionsStorage connectionsStorage;

public NewsHub(NewsService newsService, HubConnectionsStorage connectionsStorage)
{
  this.newsService = newsService;
  this.connectionsStorage = connectionsStorage;
}

public override Task OnConnectedAsync()
{
  var jwtToken = GetCurrentConnectionJwtToken();
  connectionsStorage.AddConnection(Context.ConnectionId, jwtToken);
  return Task.CompletedTask;
}

public override Task OnDisconnectedAsync(Exception exception)
{
  connectionsStorage.RemoveConnection(Context.ConnectionId);
  return Task.CompletedTask;
}

public async Task Send((string groupName, string generatedNews) news)
{
  if (!newsService.CheckTopic(news.groupName))
    throw new Exception("cannot send a news item to a group which does not exist.");

  connectionsStorage.RemoveExpiredConnections(ValidateJwtToken);

  var groupConnections = connectionsStorage.GetGroupConnections(news.groupName);
  await Clients.Clients(groupConnections).SendAsync("NewsFeed", news.generatedNews);
}

public async Task JoinGroup(string groupName)
{
  if (!newsService.CheckTopic(groupName))
    throw new Exception("cannot join a group which does not exist.");

  connectionsStorage.AddConnectionToGroup(Context.ConnectionId, groupName);

  var groupConnections = connectionsStorage.GetGroupConnections(groupName);

  await Clients.Clients(groupConnections).SendAsync("JoinGroup", groupName);

  var history = newsService.GetTopicNews(groupName);
  await Clients.Client(Context.ConnectionId).SendAsync("History", history);
}

public async Task LeaveGroup(string groupName)
{
  if (!newsService.CheckTopic(groupName))
    throw new Exception("cannot leave a group which does not exist.");

  var groupConnections = connectionsStorage.GetGroupConnections(groupName);

  await Clients.Clients(groupConnections).SendAsync("LeaveGroup", groupName);
  connectionsStorage.RemoveConnectionFromGroup(Context.ConnectionId, groupName);
}

private string GetCurrentConnectionJwtToken() => "fake jwt token "+Random.Next(4);
private bool ValidateJwtToken(string jwtToken) => Random.NextDouble() >= 0.5;

private static readonly Random Random = new Random();
}
}

这只是一个了解想法的示例。对其进行修改以适合您的需求。 希望对您有帮助)

答案 1 :(得分:0)

我能想到的唯一解决方案是建立连接和令牌的映射。遍历令牌,如果令牌过期,则断开相应的客户端。