If i use a proxy, then SignalR (WebSockets) is working, but not Identity (Cookies). If i don´t use a proxy Identity is working, but not SignalR.
The setup is a little odd in this project and i am not allowed to change it. The login page is served from backend with an MVC view, when logged in, the Angular app is loaded. This have worked fine until i tryed adding SignalR.
var builder = WebApplication.CreateBuilder(args);
...
ConfigureIdentity(builder);
ConfigureMVC(builder);
...
// Angular SPA files will be served from this directory
builder.Services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
ConfigureCORS(builder);
// SignalR
builder.Services.AddSignalR();
var app = builder.Build();
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles(new StaticFileOptions {});
app.UseRouting();
app.UseCors(CORS_ALLOWED_ORIGINS);
app.UseAuthentication();
app.UseAuthorization();
// SignalR
app.UseWebSockets();
app.MapHub<SignalRMessagesHub>("/signalr-messages", (o) => {
o.Transports = HttpTransportType.WebSockets;
});
app.MapControllers();
app.UseMvc(); // The login page uses mvc.
// Serve the angular app and set some options, catch-all route to angular app
// Late in the chain, so that other middleware for serving static files, MVC actions, etc., takes precedence.
app.UseSpa((spa) =>
{
spa.Options.SourcePath = "../../../Frontend_App";
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
{
OnPrepareResponse = (context) =>
{
var isAuthenticated = context.Context.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated)
{
context.Context.Response.Redirect("/login");
}
if (string.Equals(context.File.Name, "index.html"))
{
context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
context.Context.Response.Headers.Add("Expires", "-1");
}
}
};
if (app.Environment.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
spa.Options.StartupTimeout = TimeSpan.FromMinutes(10);
// If i add this line & remove above, then i need to start Angular with "ng serve".
// But doing so will make Identity to stop working... and SignalR start working..
//spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
}
});
app.Run();
I i have seen working examples with SignalR and Angular but not where they also have Identity and a MVC login page. They all have a diffrent setup where the login page is in the Angular app and also uses JWT.
I don´t understand why SignalR can´t connect with frontend. Anyone that can point me in the right direction to solve this?