AppHarbor Reverse Proxy causes SSL and app issues.UseOAuthBearerTokens ASP.NET MVC 5

Applications in AppHarbor sit behind the NGINX load balancer. Because of this, all requests that fall into the client application will be processed via HTTP, since SSL will be processed by this interface.

ASP.NET MVC OAuth 2 OAuthAuthorizationServerOptions has options for restricting access to token requests for HTTPS use only. The problem is that, unlike Controller or ApiController, I don’t know how to allow these forwarded requests when I specify AllowInsecureHttp = false.

In particular, in app startup / config:

  app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions {
            AllowInsecureHttp = true,
   });

You need to somehow perform this check inside, and if it is true, treat it like SSL:

HttpContext.Request.Headers["X-Forwarded-Proto"] == "https"

Here, as I do, using the MVC controller, applying a special filter attribute: https://gist.github.com/runesoerensen/915869

+4
source share
1 answer

You can try and register some middleware that can modify requests based on the headers sent by nginx. You might also want to set the remote IP address to a header value X-Forwarded-For.

Something like this should work (unverified):

public class AppHarborMiddleware : OwinMiddleware
{
    public AppHarborMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override Task Invoke(IOwinContext context)
    {
        if (string.Equals(context.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase))
        {
            context.Request.Scheme = "https";
        }

        var forwardedForHeader = context.Request.Headers["X-Forwarded-For"];
        if (!string.IsNullOrEmpty(forwardedForHeader))
        {
            context.Request.RemoteIpAddress = forwardedForHeader;
        }
        return Next.Invoke(context);
    }
}

Be sure to add it before you configure middleware for authentication:

app.Use<AppHarborMiddleware>();
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = false,
});
+6
source

Source: https://habr.com/ru/post/1544532/


All Articles