Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/3.1] Pass access token as query string when running SignalR in the browser #20466

Merged
merged 2 commits into from
Apr 14, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ private static class Log
private static readonly Action<ILogger, HttpTransportType, Exception> _transportStarted =
LoggerMessage.Define<HttpTransportType>(LogLevel.Debug, new EventId(18, "TransportStarted"), "Transport '{Transport}' started.");

private static readonly Action<ILogger, Exception> _serverSentEventsNotSupportedByBrowser =
LoggerMessage.Define(LogLevel.Debug, new EventId(19, "ServerSentEventsNotSupportedByBrowser"), "Skipping ServerSentEvents because they are not supported by the browser.");

public static void Starting(ILogger logger)
{
_starting(logger, null);
Expand Down Expand Up @@ -167,6 +170,11 @@ public static void TransportStarted(ILogger logger, HttpTransportType transportT
{
_transportStarted(logger, transportType, null);
}

public static void ServerSentEventsNotSupportedByBrowser(ILogger logger)
{
_serverSentEventsNotSupportedByBrowser(logger, null);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public partial class HttpConnection : ConnectionContext, IConnectionInherentKeep
private bool _started;
private bool _disposed;
private bool _hasInherentKeepAlive;
private bool _isRunningInBrowser;

private readonly HttpClient _httpClient;
private readonly HttpConnectionOptions _httpConnectionOptions;
Expand Down Expand Up @@ -150,6 +151,14 @@ public HttpConnection(HttpConnectionOptions httpConnectionOptions, ILoggerFactor
_httpClient = CreateHttpClient();
}

_isRunningInBrowser = Utils.IsRunningInBrowser();


if (httpConnectionOptions.Transports == HttpTransportType.ServerSentEvents && _isRunningInBrowser)
{
throw new ArgumentException("ServerSentEvents can not be the only transport specified when running in the browser.", nameof(httpConnectionOptions));
}

_transportFactory = new DefaultTransportFactory(httpConnectionOptions.Transports, _loggerFactory, _httpClient, httpConnectionOptions, GetAccessTokenAsync);
_logScope = new ConnectionLogScope();

Expand Down Expand Up @@ -365,6 +374,13 @@ private async Task SelectAndStartTransport(TransferFormat transferFormat, Cancel
continue;
}

if (transportType == HttpTransportType.ServerSentEvents && _isRunningInBrowser)
{
Log.ServerSentEventsNotSupportedByBrowser(_logger);
transportExceptions.Add(new TransportFailedException("ServerSentEvents", "The transport is not supported in the browser."));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is that? Is it because the http client isn't fetch based?

Copy link
Member Author

@wtgodbe wtgodbe Apr 3, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From @BrennanConroy on the other PR:

Was thinking about this over the weekend and realized we need to do something about SSE.

Right now it doesn't work because we use an HttpClient GET with "text/event-stream" Accept header. Which doesn't work in the browser, we use the EventSource API in the Typescript client to do a streaming response.

We might just have to disable SSE when running the .NET client in the browser.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe @BrennanConroy tried it and it didn’t work. We can always make adjustments and reenable. Plus, we are considering deprecating SSE in general.

continue;
}

try
{
if ((transportType & _httpConnectionOptions.Transports) == 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Runtime.InteropServices;

namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
{
Expand Down Expand Up @@ -41,5 +42,10 @@ internal static Uri AppendQueryString(Uri url, string qs)
builder.Query = newQueryString;
return builder.Uri;
}

internal static bool IsRunningInBrowser()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this what we agreed on with the BCL team?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guidance I got from @pranavkm and @anurse was that this is the pattern going forward

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what we have now. I believe discussions are ongoing and we can react later if necessary. Personally I’d prefer a string like “browser” since WASM is not browser-specific, but 🤷‍♀️

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The string needs to be browser. Can we circle back and make sure? Last I checked we were leaning in that direction. I worry about future breaking changes

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pranavkm @danroth27 @SteveSandersonMS What's the story here? Is there a final decision on the string to use for detecting the browser? We'd really like to get this in and right the first time before 3.1.4 closes on Tuesday.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI @lewing

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any idea when that'll happen? I guess we'll need to either wait, or change the string at the same time they change it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change should land before 3.2-RC. Since this change aligns with the RTM release, using BROWSER might be the correct thing to do. Again @lewing in case you think otherwise.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can change it now to BROWSER. The timing should be fine (3.1.4 is shipping no earlier than 3.2 GA, by the current schedule). It's not going to fail if the string is wrong, right? It just won't light up the fixed behavior until you're running on a runtime with the updated OS platform string.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not going to fail if the string is wrong, right? It just won't light up the fixed behavior until you're running on a runtime with the updated OS platform string.

That'd be my understanding, it won't fail, it just won't do anything until the corresponding change is made. I'll make the change

}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO.Pipelines;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
Expand All @@ -23,6 +24,7 @@ internal partial class WebSocketsTransport : ITransport
private readonly ILogger _logger;
private readonly TimeSpan _closeTimeout;
private volatile bool _aborted;
private bool _isRunningInBrowser;

private IDuplexPipe _transport;

Expand Down Expand Up @@ -87,6 +89,8 @@ public WebSocketsTransport(HttpConnectionOptions httpConnectionOptions, ILoggerF

// Ignore the HttpConnectionOptions access token provider. We were given an updated delegate from the HttpConnection.
_accessTokenProvider = accessTokenProvider;

_isRunningInBrowser = Utils.IsRunningInBrowser();
}

public async Task StartAsync(Uri url, TransferFormat transferFormat, CancellationToken cancellationToken = default)
Expand All @@ -113,7 +117,17 @@ public async Task StartAsync(Uri url, TransferFormat transferFormat, Cancellatio
var accessToken = await _accessTokenProvider();
if (!string.IsNullOrEmpty(accessToken))
{
_webSocket.Options.SetRequestHeader("Authorization", $"Bearer {accessToken}");
// We can't use request headers in the browser, so instead append the token as a query string in that case
if (_isRunningInBrowser)
{
var accessTokenEncoded = UrlEncoder.Default.Encode(accessToken);
accessTokenEncoded = "access_token=" + accessTokenEncoded;
resolvedUrl = Utils.AppendQueryString(resolvedUrl, accessTokenEncoded);
}
else
{
_webSocket.Options.SetRequestHeader("Authorization", $"Bearer {accessToken}");
}
}
}

Expand Down