How to set redirect_uri protocol to HTTPS in Azure Web Apps

I had the problem myself. I took a deep dive into Microsoft's Microsoft.AspNetCore.Authentication and found out how they constructed the redirect url:

protected string BuildRedirectUri(string targetPath)
        => Request.Scheme + "://" + Request.Host + OriginalPathBase + targetPath;

Because the Web App already forces HTTPS this can be solved with the following code in the Startup.cs

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
      ForwardedHeaders = ForwardedHeaders.XForwardedProto
});

You only have to add this reference:

using Microsoft.AspNetCore.HttpOverrides;

By consulting these links:

  • This question ;-)
  • https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?tabs=aspnetcore2x&view=aspnetcore-2.2#configure-a-reverse-proxy-server
  • https://github.com/aspnet/Security/issues/1901

And applying 3 changes to the configuration, I got everything working on a Linux App Plan.

Step 1 : configure the ForwardedHeadersOptions

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.RequireHeaderSymmetry = false;
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;

    // TODO : it's a bit unsafe to allow all Networks and Proxies...
    options.KnownNetworks.Clear();
    options.KnownProxies.Clear();
});

Step 2 : UseForwardedHeaders in the public void Configure(IApplicationBuilder app, IHostingEnvironment env) method

app.UseForwardedHeaders();

Step 3 : Only use UseHttpsRedirection for production

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    // Forward http to https (only needed for local development because the Azure Linux App Service already enforces https)
    app.UseHttpsRedirection();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}