Skip to content

Commit

Permalink
Server sent events are not sent (#959)
Browse files Browse the repository at this point in the history
* fix: AddCustomIdentity in SseServer

* fix: use AddAuthorizationBuilder instead of AddAuthorization

* fix: url encode address in request to sse server

* chore: remove unnecessary ResponseCaching middleware

* chore: don't set ShowPII, not even in case of a Development environment

* fix: catch OperationCanceledException to avoid it from being logged

* fix: don't return anything from SseController.Subscribe method. Otherwise the response writer throws in case of a cancellation

* chore: add cancellation token
  • Loading branch information
tnotheis authored Dec 2, 2024
1 parent 1035c98 commit db30b05
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 20 deletions.
19 changes: 10 additions & 9 deletions Applications/SseServer/src/SseServer/Controllers/SseController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Backbone.BuildingBlocks.API;
using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext;
using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext;
using Backbone.Modules.Devices.Application.PushNotifications.Commands.DeleteDeviceRegistration;
using Backbone.Modules.Devices.Application.PushNotifications.Commands.UpdateDeviceRegistration;
using MediatR;
Expand All @@ -25,7 +24,7 @@ public SseController(IEventQueue eventQueue, IUserContext userContext, IMediator

[HttpGet("/api/v1/sse")]
[Authorize]
public async Task<IActionResult> Subscribe()
public async Task Subscribe(CancellationToken cancellationToken)
{
var address = _userContext.GetAddress().Value;

Expand All @@ -34,7 +33,7 @@ await _mediator.Send(new UpdateDeviceRegistrationCommand
Handle = "sse-handle", // this is just some dummy value; the SSE connector doesn't use it
AppId = "sse-client", // this is just some dummy value; the SSE connector doesn't use it
Platform = "sse"
});
}, cancellationToken);

Response.StatusCode = 200;
Response.Headers.CacheControl = "no-cache";
Expand All @@ -56,8 +55,11 @@ await _mediator.Send(new UpdateDeviceRegistrationCommand
}
catch (ClientAlreadyRegisteredException)
{
return BadRequest(HttpError.ForProduction("error.platform.sseClientAlreadyRegistered",
"An SSE client for your identity is already registered. You can only register once per identity.", ""));
// if it is already registered, everything is fine
}
catch (OperationCanceledException)
{
// this is expected when the client disconnects
}
catch (Exception ex)
{
Expand All @@ -66,10 +68,9 @@ await _mediator.Send(new UpdateDeviceRegistrationCommand
finally
{
_eventQueue.Deregister(address);
await _mediator.Send(new DeleteDeviceRegistrationCommand());
// we must NOT pass the cancellation token here, because otherwise the device registration would not be deleted in case the request was cancelled
await _mediator.Send(new DeleteDeviceRegistrationCommand(), CancellationToken.None);
}

return Ok();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public static void AddCustomAspNetCore(this IServiceCollection services,
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
});

services.AddAuthentication().AddJwtBearer(options =>
services.AddAuthentication().AddJwtBearer("default", options =>
{
var privateKeyBytes = Convert.FromBase64String(configuration.Authentication.JwtSigningCertificate);
#pragma warning disable SYSLIB0057 // The constructor is obsolete. But I didn't manage to get the suggested alternative to work.
Expand All @@ -75,7 +75,13 @@ public static void AddCustomAspNetCore(this IServiceCollection services,
options.TokenValidationParameters.ValidateIssuer = false;
options.TokenValidationParameters.ValidateAudience = false;
});
services.AddAuthorization();

services.AddAuthorizationBuilder()
.AddDefaultPolicy("default", policy =>
{
policy.AddAuthenticationSchemes("default");
policy.RequireAuthenticatedUser();
});

services.AddHttpContextAccessor();

Expand Down
12 changes: 4 additions & 8 deletions Applications/SseServer/src/SseServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
using Backbone.Tooling.Extensions;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Logging;
using Serilog;
using Serilog.Exceptions;
using Serilog.Exceptions.Core;
Expand Down Expand Up @@ -75,7 +74,7 @@ static WebApplication CreateApp(string[] args)
)
.UseServiceProviderFactory(new AutofacServiceProviderFactory());

ConfigureServices(builder.Services, builder.Configuration);
ConfigureServices(builder.Services, builder.Configuration, builder.Environment);

var app = builder.Build();
Configure(app);
Expand All @@ -88,7 +87,7 @@ static WebApplication CreateApp(string[] args)
return app;
}

static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
static void ConfigureServices(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
{
services.ConfigureAndValidate<Configuration>(configuration.Bind);

Expand Down Expand Up @@ -117,6 +116,8 @@ static void ConfigureServices(IServiceCollection services, IConfiguration config
options.KnownProxies.Clear();
});

services.AddCustomIdentity(environment);

services.AddPushNotifications(parsedConfiguration.Modules.Devices.Infrastructure.PushNotifications);
}

Expand All @@ -141,16 +142,11 @@ static void Configure(WebApplication app)
.AddCustomHeader("X-Frame-Options", "Deny")
);

if (app.Environment.IsDevelopment())
IdentityModelEventSource.ShowPII = true;

app.UseAuthentication().UseAuthorization();

app.MapControllers();

app.MapHealthChecks("/health");

app.UseResponseCaching();
}

static void LoadConfiguration(WebApplicationBuilder webApplicationBuilder, string[] strings)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using System.Web;

namespace Backbone.Modules.Devices.Infrastructure.PushNotifications.Connectors.Sse;

Expand All @@ -16,7 +17,7 @@ public SseMessageBuilder(string recipient, string eventName)

public HttpRequestMessage Build()
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{_recipient}/events")
var request = new HttpRequestMessage(HttpMethod.Post, $"{HttpUtility.UrlEncode(_recipient)}/events")
{
Content = JsonContent.Create(new EventPayload(_eventName))
};
Expand Down

0 comments on commit db30b05

Please sign in to comment.