Code Monkey home page Code Monkey logo

aspnetcore.spayarp's Introduction

AspNetCore.SpaYarp

NuGet
Supported ASP.NET Core versions:

AspNetCore.SpaYarp version .NET Version
1.1.0 3.1, 5.0 and 6.0
2.0.0 6.0 and 7.0

With ASP.NET Core Preview 4, the ASP.NET Core team introduced a new experience for SPA templates.

The main benefit of this new experience is that it's possible to start and stop the backend and client projects independently.

This is a very welcome change and speeds up the development process. But it also includes another more controversial change. The old templates served the client application as part of the ASP.NET Core host and forwarded the requests to the SPA. With the new templates, the URL of the SPA is used to run the application, and requests to the backend get forwarded by a built-in proxy of the SPA dev server.

AspNetCore.SpaYarp uses a different approach. Instead of using the SPA dev server to forward requests to the host/backend, it uses YARP to forward all requests that can't be handled by the host to the client application. It works similar to the old templates, but with the advantage of the new templates to start and stop the backend and client projects independently.

The following graphic shows the differences:

Overview

To get more insights you can read my blog post An alternative approach to the ASP.NET Core SPA templates using YARP.

Running the sample

To run the sample, open the solution in Visual Studio and start the Net6Startup or Net7WebApplicationBuilder project. It reuses an existing SPA dev server if the client app is already running (started manually in a terminal or VS Code) or it starts a new one.

Debugging

It's possible to debug the .NET code and the SPA at the same time with different editors. To use Visual Studio Code to debug the SPA, create a launch.json file as described in the docs. But instead of the URL of the SPA, the URL of the .NET host must be used.

This is the launch.json file used in the sample projects:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-msedge",
      "request": "launch",
      "name": "Launch Edge against localhost",
      "url": "https://localhost:7113",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

Using AspNetCore.SpaYarp

Configure settings in project file

<PropertyGroup>
    <!-- SpaYarp configuration -->
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaClientUrl>https://localhost:44478</SpaClientUrl>
    <SpaLaunchCommand>npm start</SpaLaunchCommand>
    <!-- Change the timeout of the proxy (defaults to 120 seconds) 
    <SpaProxyTimeoutInSeconds>120</SpaProxyTimeoutInSeconds> -->
    <!-- Optionally forward only request starting with the specified path 
    <SpaPublicPath>/dist</SpaPublicPath> -->
</PropertyGroup>

Setup with WebApplication builder

Use AddSpaYarp() to register the services and UseSpaYarp() to add the middlware and configure the route endpoint.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
// This file gets not published when using "dotnet publish".
// The services get not added and the proxy is not used when the file does not exist.
builder.Services.AddSpaYarp();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

// The middlewares get only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
app.UseSpaYarp();

// If the SPA proxy is used, this will never be reached.
app.MapFallbackToFile("index.html");

app.Run();

Setup with Startup.cs

Use AddSpaYarp() to register the services, UseSpaYarpMiddleware() to add the middlware, and MapSpaYarp() to configure the route endpoint.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        // Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
        // This file gets not published when using "dotnet publish".
        // The services get not added and the proxy is not used when the file does not exist.
        services.AddSpaYarp();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        // The middleware gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
        app.UseSpaYarpMiddleware();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            // The route endpoint gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
            endpoints.MapSpaYarp();

            // If the SPA proxy is used, this will never be reached.
            endpoints.MapFallbackToFile("index.html");
        });
    }
}

Multiple SPA Sites

This feature lets you combine multiple SPA dev servers into one, with each providing its site to a separate path.

There is a sample demonstrating how to do this as well.

app.UseSpaYarpMiddleware();
app.MapSpaYarp("one", "https://localhost:44478");
app.MapSpaYarp("two", "https://localhost:44479");

Migrate from SpaProxy

This guide assumes that you are using the default ASP.NET Core with Angular Template (but should work the same for other frameworks too).
Thanks to @mdowais for this guide.

Step 1: Add the Nuget Package
https://www.nuget.org/packages/AspNetCore.SpaYarp

Step 2: Remove Old SpaProxy Package
Remove the Package Microsoft.AspNetCore.SpaProxy. As it is not needed for this implementation.

Note: The default template adds a Environment Variable ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", in the launchSettings.json (Debug Properties in Visual Studio). Which has to be removed, so that you don't see an annoying Exception thrown that "Microsoft.AspNetCore.SpaProxy" is 404.

Step 3: Remove proxy.conf.js
Remove the proxy.conf.js file that contains the proxy config for the client dev server.
And remove the reference to this file from the angular.json file too.

Step 4: Change Project Properties
In your Project Settings (csproj) -> PropertyGroup, change the following

SpaProxyServerUrl to SpaClientUrl
SpaProxyLaunchCommand to SpaLaunchCommand

Step 5: Add the Services and Usings in your Program.cs

// First
builder.Services.AddSpaYarp()

//Second
app.UseSpaYarp();

aspnetcore.spayarp's People

Contributors

berhir avatar buchatsky avatar fuzzlebuck avatar johncampionjr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnetcore.spayarp's Issues

Cannot proxy to self signed cert over https

When I run my app, I get the following error, which is obvious, because the self signed cert is of course not trustworthy :)

I am wondering why this error does not seem to occur for other users of SpaYarp though ... Am I missing some config?

info: Yarp.ReverseProxy.Forwarder.HttpForwarder[48]
      Request: An error was encountered before receiving a response.
      System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
       ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

Make Proxied Request Path Configurable

I haven't been able to fully test this yet (as per my other issue) but from reading the code, I think that the line the line endpoints.Map("/{**catch-all}" in IEndpointRouteBuilderExtensions would make it so the .Net application itself can't have a "catch all" handler - which is I think a relatively common requirement.

I need to be able to have only certain requests proxied - e.g. those starting with /dist/ and other paths specific to the hot reloading features of Webpack. That would let the .Net application handle all other requests, including not matched ones.

I'm thinking that MapSpaYarp should at very least accept the string pattern as a parameter

Adjust log level

The current logs from the proxy seem to spam the log stream. Are there any way to filter so f.ex only warnings from the proxy is logged?

I'm currently using Serilog and this is a sample from the console log:

[14:24:50 INF] Received HTTP/1.1 response 200.
[14:24:50 INF] SPA client is ready.
[14:24:50 INF] Proxying to http://localhost:6363/node_modules/.vite/deps/chunk-N7AMQ326.js?v=4cd2ae21 HTTP/2 RequestVersionOrLower no-streaming
[14:24:50 INF] SPA client is ready.
[14:24:50 INF] SPA client is ready.
[14:24:50 INF] Proxying to http://localhost:6363/node_modules/.vite/deps/@azure_msal-common_dist_error_AuthError.js?v=4cd2ae21 HTTP/2 RequestVersionOrLower no-streaming
[14:24:50 INF] SPA client is ready.
[14:24:50 INF] Proxying to http://localhost:6363/node_modules/.vite/deps/@equinor_eds-core-react.js?v=4cd2ae21 HTTP/2 RequestVersionOrLower no-streaming
[14:24:50 INF] Received HTTP/1.1 response 200.
[14:24:50 INF] SPA client is ready.

This makes it impossible to look for the log messages from our own application...

I tried to override the Serilog configuration with "AspNetCore.SpaYarp": "Warning", but that didn't seem to work.

If using a fallback policy there is no way to bypass authentication for the SpaProxy

The issue I experience may be an edge case but if you configure you application with a fallback authorization policy it will force you to authenticate before proxying to your spa.
Example fallback policy

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

I download the source code and determined if you add a configuration option that allows you to add the AllowAnonymousAttribute to the endpoint it fixes the issue

Example Fix in IEndpointRouteBuilderExtensions.cs

endpoints.Map(string.Format("{0}/{{**catch-all}}", spaOptions.PublicPath), async httpContext =>
        {
            var error = await forwarder.SendAsync(httpContext, spaOptions.ClientUrl, httpClient, requestOptions, transformer);
            // Check if the proxy operation was successful
            if (error != ForwarderError.None)
            {
                var errorFeature = httpContext.Features.Get<IForwarderErrorFeature>();
                var exception = errorFeature?.Exception;
            }
        }).Add(builder => { 
            if (spaOptions.ForceAnonymous)
            {
                builder.Metadata.Add(new AllowAnonymousAttribute());
            }              
        });

From a design pov not sure if you want to pass an options object to MapSpaYarp() or just add another property to SpaDevelopmentServerOptions

Update to .NET7 and Yarp 2.0.0

An update to Yarp.ReverseProxy 2.0.0 would require to drop support for netcoreapp3.1 (which is out of support since December 13 2022) and .NET 5 (which is out of support since May 10, 2022) but this fixes issues with web sockets opened by the live-refresh functionality of ng serve. These Requests produce errors like

An unhandled exception has occurred while executing the request.
System.NotSupportedException: Unsupported request method 'CONNECT'.  
at Yarp.ReverseProxy.Forwarder.RequestUtilities.GetHttpMethod(String method)
   at Yarp.ReverseProxy.Forwarder.HttpForwarder.CreateRequestMessageAsync(HttpContext context, String destinationPrefix, HttpTransformer transformer, ForwarderRequestConfig requestConfig, Boolean isStreamingRequest, ActivityCancellationTokenSource activityToken)
...

In addition, .NET7 was release November 8 2022, so it would be good to add explicit support.
If desired, I guess I can provide a pull request.

Can it be configured when ASP.NET core is running on IIS (only in development)

Development servers have the issue they behave not exactly as applications under IIS (e.g. app pool identity has less access than process running under current user). That's why I like to run asp.net core applications under IIS in development as well, because potentially issues due to less rights of the app pool identity will show up immediately.

Any guideline if index page is a server side Razor page?

Hi,
In our ASP.NET/Angular application we are not using index.html, rather we do have index.cshtml Razor page and in the program.cs file we have this as very last setting:

app.MapFallbackToController("Index", "Home");

and we add references to the generated JavaScript file hard-coded in the index.cshtml file:

    <script src="~/dist/runtime.js" asp-append-version="true"></script>
    <script src="~/dist/polyfills.js" asp-append-version="true"></script>
    <script src="~/dist/main.js" asp-append-version="true"></script>
    <script src="~/dist/vendor.js" asp-append-version="true"></script>

Still we want to take advantage of hot module reloading the Angular/Webpack provide.

Do you have any recommendation?

[Feature Request] Start the launch Command in a separate process

Hello, The application is executing the Launch Command (Process.Start), if it was not started seperately. But it also closes the process when the Debugging stops/restarts. As stated in the line below

private void LaunchDevelopmentClient()

But, it would make it more better if, it stayed even after stopping, which would be a great improvement when dealing with large SPA application.

The Stopping process is called using powershell, and I guess it could be started using the same way, which would keep it alive even when stopped debugging

I suggest to create a property in SpaDevelopmentServerOptions, which allows a functionality like LaunchDevServerIndependently, which wont close when debugger is stopped / restarted.

It makes it easy, so that the developer doesnt have to start the devserver manually/independently.

WriteSpaConfigurationToDisk Build Target Not Executed

The WriteSpaConfigurationToDisk target doesn't seem to get executed. I see AssignTargetPaths being executed, but not WriteSpaConfigurationToDisk, so the spa.proxy.json file never gets generated. I've checked in AppDomain.BaseDirectory folder and the file isn't in there.

Here's AssignTargetPaths being executed:

1>Target AssignTargetPaths:
1>  Using "AssignTargetPath" task from assembly "Microsoft.Build.Tasks.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

But WriteSpaConfigurationToDisk isn't found in the logs at all.

Instead of relying on this build task, based on values from the csproj, I would prefer to be able to configure the root/client URL from the C# code, e.g. in a callback to UseSpaYarpMiddleware. To only execute it in development mode I can simply wrap the addition of SpaYarp with either #if DEBUG or an IWebHostEnvironment.IsDevelopment() call

SSL self signed certificate

Hello,

I have an error when the middleware tries to see if the spa is starter

info: Yarp.ReverseProxy.Forwarder.HttpForwarder[48] Request: An error was encountered before receiving a response. System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

Is there any way to make it work ?

Thank you so much for your help ๐Ÿ˜„

Using PublicPath to check if Spa Client server is running

Currently SpaYarp uses the root ClientUrl to check if SpaClient server is running, even when PublicPath is defined.
Formerly I used webpack to start webpack dev srver, and I specified static: ['src'] in devServer options to direct the root request to the static src/index.html.
But now I tried to switch to Angular cli and found out that it does not allow to specify 'static' option, so SpaYarp needs to access PublicPath/PublicPath to detect the presense of spa server (index.html also needs to exist in PublicPath folder).

License

Hi, what is the license of this source code?

[Guide] Installation

I was trying to implement this, but couldn't find a good Installation Guide, but figured it out. Posting this as a issue, for people to see.

This guide assumes that you are using the default ASP.NET Core with Angular Template, but must work with basically all.

Step 1: Add the Nuget Package

https://www.nuget.org/packages/AspNetCore.SpaYarp

Step 2: Remove Old SpaProxy Package

Remove the Package Microsoft.AspNetCore.SpaProxy. As it is not needed for this implementation.

Note : The default template adds a Environment Variable ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", in the launchSettings.json (Debug Properties in Visual Studio). Which has to be removed, so that you don't see an annoying Exception thrown that "Microsoft.AspNetCore.SpaProxy" is 404.

Step 3: Change Project Properties

In your Project Settings (csproj) -> PropertyGroup, change the following

  1. SpaProxyServerUrl to SpaClientUrl
  2. SpaProxyLaunchCommand to SpaLaunchCommand

Step 4: Add the Services and Usings in your Program.cs

// First
builder.Services.AddSpaYarp()

//Second
app.UseSpaYarp();

How to set MaxTimeoutInSeconds to 9999

angular build is slow may be take 3 min
how to set MaxTimeoutInSeconds ?Thx is SpaProxyTimeoutInSeconds?
and in sourcecode where is the nuget package: Yarp.ReverseProxy.Forwarder

.net core 3.1 usage

I'm wondering if there is a possibility of using this approach on .net core 3.1? thank you.

MapSpaYarp prevents usage of AllowAnonymous

We are using Authentication and Authorization in our application and enabled them by default if no authorize attribute is used.
In such scenarios, MapSpaProxy hides the access to the route configuration.

I created PR #31 which removes the optional policyName attribute and adds IEndpointConventionBuilder as return value instead.
This allows to decide how to handle route conventions similar to when controllers or static files are mapped.

app = builder.Build();
...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
...
app.UseSpaYarpMiddleware();
// allow anonymous access to fallback routes (index.html and angular dev-server assets)
app.MapSpaYarp().AllowAnonymous();

// alternative usage:
app.MapSpaYarp().RequireAuthorization(); // requires the default policy
app.MapSpaYarp().RequireAuthorization("SpaYarpPolicyName"); // requires a custom policy
// mixed setup with authorized and public SPA proxy paths
app.MapSpaYarp("EndpointPath1","https://localhost:7890").RequireAuthorization();
app.MapSpaYarp("EndpointPath2","https://localhost:7880").AllowAnonymous();

As quickfix, I added a custom implementation of the MapSpaYarp method in our project but it would be nice if you can merge it and create a new nuget package version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.