TeamDman
TeamDman

Reputation: 1025

How to path-based reverse proxy app service behind application gateway?

I have an application gateway configured with my wildcard certificate that I want to use to proxy myapp.azurewebsites.net (an ASP.NET core application) behind myapp.mywebsite.net/mypath.

I have an existing site running on myapp.mywebsite.net configured in the gateway, but I want just the /mypath route to point to the app service. How can I accomplish this?

Upvotes: 0

Views: 1432

Answers (1)

TeamDman
TeamDman

Reputation: 1025

Step 1 - Configuring the Gateway

  1. Add a new backend target for myapp.azurewebsites.net
  2. Add a new http setting, enable hostname override with specific domain name for myapp.azurewebsites.net. Don't add the path override, we want the /mypath to be passed to the app service.
  3. Edit the existing path-based rule for the site:
    1. Add new path-based rule
      1. path=/mypath/*
      2. name=mypathname // can be whatever
      3. httpsetting=the one we just made
      4. backendpool=the one we just made

This will point myapp.mywebsite.net/mypath to the site

Step 2 - Configuring the Application

Startup.cs - Configure

See here for more info.

Add the following to the very start of the Configure method. We want headers to be adjusted before all other middleware happens.

app.UseForwardedHeaders(); // Enable hostname to be derived from headers added by app gateway
app.UsePathBase("/mypath"); // Tell ASP.NET that we have a base path

See here for debugging help.

Startup.cs - ConfigureServices

We need to tell ASP.NET to trust the gateway headers

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.AllowedHosts.Add("myapp.mywebsite.net");
    options.KnownProxies.Add(IPAddress.Parse("10.my.gateway.ip"));
});

If you are using

services.AddMicrosoftIdentityWebAppAuthentication(config);

for auth, we need to override the reply url so it points to myapp.mywebsite.net/mypath/signin-oidc instead of myapp.azurewebsites.net/signin-oidc. This can be done with:

if (!env.IsDevelopment())
{
    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        // options.SaveTokens = true; // this saves the token for the downstream api
        options.Events = new OpenIdConnectEvents
        {
            OnRedirectToIdentityProvider = async ctxt =>
            {
                ctxt.ProtocolMessage.RedirectUri = "https://myapp.mywebsite.net/mypath/signin-oidc";
                await Task.Yield();
            }
        };
    });
}

We only run this in dev so that running our stuff locally does the default behaviour of filling the replyurl with localhost.

Upvotes: 1

Related Questions