1

I added this simple piece of middleware to my asp.net core web app according to this post: Redirect to HTTPS

if (!env.IsLocalhost())
{
            app.Use(async (context, next) =>
            {
                if (context.Request.IsHttps)
                {
                    await next();
                }
                else
                {
                    var withHttps = "https://" + context.Request.Host + context.Request.Path;
                    context.Response.Redirect(withHttps);
                }
            });
            app.UseMiddleware<RedirectHttpMiddleware>();
} 

After deploying to Azure I have an infinite redirect loop.

I have verified that the middleware is causing the infinite loop (if I comment it out the loop goes away) and that IsHttps is indeed true.

Does anybody have a suggestion as to why this happens?

Community
  • 1
  • 1
Nikola Schou
  • 2,386
  • 3
  • 23
  • 47

2 Answers2

4

This is a known issue when running in azure. https://github.com/aspnet/IISIntegration/issues/140

You can workaround it by adding the following in ConfigureSerivces:

        services.Configure<ForwardedHeadersOptions>(options =>
        {
          options.ForwardedHeaders = ForwardedHeaders.XForwardedProto
        });
Tratcher
  • 5,929
  • 34
  • 44
  • I can confirm, this does fix the problem. Important to note that this issue has been fixed in RTM expected June 27th, 2016. – cygnim Jun 11 '16 at 04:11
  • @Tratcher Even though I believe this is the right answer I still cannot validate it because the code shown above is based on RC2 and we are using RC1. Can anyone suggest what to do when working with RC1? – Nikola Schou Jun 27 '16 at 14:11
  • RC1 was not affected by https://github.com/aspnet/IISIntegration/issues/140. Do you have `app.UseIISIntegration()` in your pipeline ahead of your redirect middleware? This was required for RC1 but is not needed for RC2. – Tratcher Jun 27 '16 at 16:44
  • @Tratcher Well, the above code does not compile at all. It seems to me that the classes implied (such as ForwardedHeadersOptions) are only available in the the RC2 assemblies. I added "Microsoft.AspNet.HttpOverrides": "1.0.0-rc1-final" to project.json but even with this the ForwardedHeadersOptions cannot be resolved. Anyway, I managed to solve it using some simpler block of code, cf. the answer posted by myself. – Nikola Schou Jun 27 '16 at 19:00
1

I managed to solve this for RC1 using this block of code:

app.Use(async (context, next) =>
            {
                String protoHeader = context.Request.Headers["X-Forwarded-Proto"];
                if (protoHeader.ToLower().Equals("https"))
                {
                    await next();
                }
                else
                {
                    var withHttps = "https://" + context.Request.Host + context.Request.Path;
                    context.Response.Redirect(withHttps);
                }
            });
Nikola Schou
  • 2,386
  • 3
  • 23
  • 47