aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Terminate SignalR connections when the corresponding token expires

Open muratg opened this issue 9 years ago • 49 comments

Originally asked in: https://github.com/aspnet/SignalR/issues/1155#issuecomment-347287019

muratg avatar Nov 27 '17 19:11 muratg

Hmm, this is tricky since the token isn't "re-transmitted" on each message. I suppose we could have code that checks the expiration of the token each time a message is received.

analogrelay avatar Nov 27 '17 22:11 analogrelay

We should make sure this is relatively easy to add, even if we don't add it ourselves. Having "filter"-style logic for incoming/outgoing HubMessages would be good.

analogrelay avatar Nov 27 '17 22:11 analogrelay

One idea is to use KeepAlive heartbeat to check token expiry. cc @anurse

muratg avatar Nov 30 '17 20:11 muratg

This is something we'll look to make possible, but I don't think we'll actually disconnect the connection ourselves. The new IConnectionHeartbeatFeature should allow the implementer of a Hub to check the token at a regular interval and then terminate the connection if they need to. I'll look at making an example of this in the preview2 milestone.

analogrelay avatar Dec 01 '17 03:12 analogrelay

We're not making this first class in 2.1.0 moving to backlog.

davidfowl avatar Feb 16 '18 23:02 davidfowl

Original question:

I understand that this has been moved to the backlog, but I've ran with @anurse's idea and added some logic to the IConnectionHeartbeatFeature to try and check the token.

The issue, however, is how to access the token from within the callback (or from inside a hub for that matter). AFAICT, the caller only has access to the identity, not the token (one could potentially include the expiration has a claim in the token, but that smells)

Any ideas are appreciated.

Update:

Actually it is possible, as for anyone that stumbles upon this thread with a similar question, there is a way to access the token via Context.Connection.GetHttpContext().GetTokenAsync(""). Make sure you configure your tokens to be saved to the AuthenticationProperties (kudos to this article for pointing me in the right direction).

jpmnteiro avatar Feb 23 '18 23:02 jpmnteiro

@muratg @anurse is this what you had in mind?

public override async Task OnConnectedAsync()
{
    var feature = Context.Connection.Features.Get<IConnectionHeartbeatFeature>();
    if (feature == null)
    {
        return;
    }

    var context = Context.Connection.GetHttpContext();
    if (context == null)
    {
        throw new InvalidOperationException("The HTTP context cannot be resolved.");
    }

    // Extract the authentication ticket from the access token.
    // Note: this operation should be cheap as the authentication result
    // was already computed when SignalR invoked the authentication handler
    // and automatically cached by AuthenticationHandler.AuthenticateAsync().
    var result = await context.AuthenticateAsync(OAuthValidationDefaults.AuthenticationScheme);
    if (result.Ticket == null)
    {
        Context.Connection.Abort();

        return;
    }

    feature.OnHeartbeat(state =>
    {
        var (ticket, connection) = ((AuthenticationTicket, HubConnectionContext)) state;

        // Ensure the access token token is still valid.
        // If it's not, abort the connection immediately.
        if (ticket.Properties.ExpiresUtc < DateTimeOffset.UtcNow)
        {
            connection.Abort();
        }
    }, (result.Ticket, Context.Connection));
}

kevinchalet avatar Feb 27 '18 12:02 kevinchalet

Yeah, that looks about right.

analogrelay avatar Feb 27 '18 16:02 analogrelay

Nice! That's a great sample for the docs.

davidfowl avatar Feb 28 '18 00:02 davidfowl

Feel free to copy it, but if you adapt it for the JWT handler, double check it works correctly 'cause I don't think the JWT handler populates the AuthenticationProperties like the aspnet-contrib validation handler does.

kevinchalet avatar Feb 28 '18 00:02 kevinchalet

Also, it might be cool to handle that more gracefully. Aborting the connection without telling the client why the server did that is a bit meh :sweat_smile:

kevinchalet avatar Feb 28 '18 00:02 kevinchalet

Aborting the connection without telling the client why the server did that is a bit meh

Seems OK to me ;P

https://media1.tenor.com/images/dd302f6644d1571646143137ad5a2320/tenor.gif?itemid=4905604

analogrelay avatar Feb 28 '18 00:02 analogrelay

Logs....

davidfowl avatar Feb 28 '18 00:02 davidfowl

Logs....

Logs are for developers, not for the SignalR client.

When an access token expires, a client is expected to renew it and re-try the request using the new token (in the OIDC world, using a refresh token or by sending a prompt=none authorization request).

If the client isn't told the connection was aborted because the access token expired, it will have to blindly renew the token, even if the connection wasn't aborted for this reason.

kevinchalet avatar Feb 28 '18 00:02 kevinchalet

I do wonder if we should consider a "Close" frame in the protocol to allow the client to have a chance to see why the connection was closed (including an Exception message, such as "Authentication token expired" or even possibly a code). The weird thing is things like Long Polling where the connection does have to stay "open" long enough for the client to poll for the Close message.

analogrelay avatar Feb 28 '18 00:02 analogrelay

Of course this could be achieved in an app-specific way in the hub itself by just invoking some method on the client before aborting the connection.

analogrelay avatar Feb 28 '18 00:02 analogrelay

Of course this could be achieved in an app-specific way in the hub itself by just invoking some method on the client before aborting the connection.

It's worth noting the heartbeat callback is not async. If you do that, you'll end up with some nasty blocking IO :sweat_smile:

kevinchalet avatar Feb 28 '18 00:02 kevinchalet

You could do a fire-and-forget task to send the message and Abort after an Ack of some kind (or a timeout).

analogrelay avatar Feb 28 '18 17:02 analogrelay

Unfortunately, this logic will now break with long polling because we did this crazy thing https://github.com/aspnet/SignalR/issues/1644. We should add a test case for this so that we can make it work.

This line:

var result = await context.AuthenticateAsync(OAuthValidationDefaults.AuthenticationScheme);

Will likely explode.

One thing you can do is look for the presence of IConnectionInherentKeepAliveFeature and disable this code if that feature exists. That means that the transport itself supports timing out (i.e. long polling) and doesn't need this heartbeat.

davidfowl avatar Mar 31 '18 09:03 davidfowl

@davidfowl would you recommend checking for the feature or checking for the type of transport on the OnConnected(...) method?

jpmnteiro avatar Mar 31 '18 10:03 jpmnteiro