Skip to content
This repository was archived by the owner on Nov 17, 2023. It is now read-only.

Commit 6933d99

Browse files
davidfowlReubenBond
authored andcommitted
Forward SignalR requests through the web app
1 parent 992b58d commit 6933d99

File tree

5 files changed

+36
-25
lines changed

5 files changed

+36
-25
lines changed

src/Web/WebMVC/AppSettings.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,5 @@
33
public class AppSettings
44
{
55
public string PurchaseUrl { get; set; }
6-
public string SignalrHubUrl { get; set; }
76
public bool UseCustomizationData { get; set; }
87
}

src/Web/WebMVC/Extensions/Extensions.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Fix samesite issue when running eShop from docker-compose locally as by default http protocol is being used
22
// Refer to https://github.com/dotnet-architecture/eShopOnContainers/issues/1391
3+
using Yarp.ReverseProxy.Forwarder;
4+
35
internal static class Extensions
46
{
57
public static void AddHealthChecks(this IServiceCollection services, IConfiguration configuration)
@@ -82,4 +84,27 @@ public static void AddAuthenticationServices(this IServiceCollection services, I
8284
options.Scope.Add("webhooks");
8385
});
8486
}
87+
88+
public static IEndpointConventionBuilder MapForwardSignalR(this WebApplication app)
89+
{
90+
// Forward the SignalR traffic to the bff
91+
var destination = app.Configuration.GetRequiredValue("PurchaseUrl");
92+
var authTransformer = new BffAuthTransfomer();
93+
var requestConfig = new ForwarderRequestConfig();
94+
95+
return app.MapForwarder("/hub/notificationhub/{**any}", destination, requestConfig, authTransformer);
96+
}
97+
98+
private sealed class BffAuthTransfomer : HttpTransformer
99+
{
100+
public override async ValueTask TransformRequestAsync(HttpContext httpContext, HttpRequestMessage proxyRequest, string destinationPrefix, CancellationToken cancellationToken)
101+
{
102+
// Set the access token as a bearer token for the outgoing request
103+
var accessToken = await httpContext.GetTokenAsync("access_token");
104+
105+
proxyRequest.Headers.Authorization = new("Bearer", accessToken);
106+
107+
await base.TransformRequestAsync(httpContext, proxyRequest, destinationPrefix, cancellationToken);
108+
}
109+
}
85110
}

src/Web/WebMVC/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
builder.AddServiceDefaults();
44

5+
builder.Services.AddHttpForwarder();
56
builder.Services.AddControllersWithViews();
67

78
builder.Services.AddHealthChecks(builder.Configuration);
@@ -28,6 +29,7 @@
2829
app.MapControllerRoute("default", "{controller=Catalog}/{action=Index}/{id?}");
2930
app.MapControllerRoute("defaultError", "{controller=Error}/{action=Error}");
3031
app.MapControllers();
32+
app.MapForwardSignalR();
3133

3234
WebContextSeed.Seed(app, app.Environment);
3335

src/Web/WebMVC/Views/Shared/_Layout.cshtml

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -86,35 +86,23 @@
8686

8787
@RenderSection("scripts", required: false)
8888

89-
90-
@using Microsoft.AspNetCore.Authentication;
91-
@using Microsoft.Extensions.Options
92-
@inject IOptions<AppSettings> settings
93-
9489
<script type="text/javascript">
9590
if ('@User.Identity.IsAuthenticated' === 'True') {
9691
var timerId;
9792
98-
stablishConnection((conn) => registerNotificationHandlers(conn));
93+
connect();
9994
}
10095
101-
function stablishConnection(cb) {
96+
async function connect() {
10297
let connection = new signalR.HubConnectionBuilder()
103-
.withUrl('@settings.Value.SignalrHubUrl/hub/notificationhub', {
104-
accessTokenFactory: () => {
105-
return "Authorization", getToken();
106-
}
107-
})
98+
.withUrl('/hub/notificationhub')
10899
.withAutomaticReconnect()
109-
.build();
110-
111-
connection.start().then(function () {
112-
console.log('User Registered to Signalr Hub');
113-
cb(connection);
114-
});
115-
}
100+
.build();
101+
102+
await connection.start();
103+
104+
console.log('User Registered to Signalr Hub');
116105
117-
function registerNotificationHandlers(connection) {
118106
connection.on("UpdatedOrderState", (message) => {
119107
toastr.success('Updated to status: ' + message.status, 'Order Id: ' + message.orderId);
120108
if (window.location.pathname.split("/").pop() === 'Order') {
@@ -123,10 +111,6 @@
123111
});
124112
}
125113
126-
function getToken() {
127-
return '@Context.GetTokenAsync("access_token").Result';
128-
}
129-
130114
function refreshOrderList() {
131115
clearTimeout(timerId);
132116
timerId = setTimeout(function () {

src/Web/WebMVC/WebMVC.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
<PackageReference Include="BuildBundlerMinifier" />
2525
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
2626
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" />
27+
<PackageReference Include="Yarp.ReverseProxy" />
2728
</ItemGroup>
2829

2930
<ItemGroup>

0 commit comments

Comments
 (0)