One of the previous articles
described a problem about redirects from an application using the provided Host
header which changes when an application gateway comes in between the client
and the application. This article describes a fix.
When an application is reached directly, it gets the host as
"context.Request.Host" and the remote IP address as
"context.Connection.RemoteIpAddress" which the application uses to
create redirects with Location header. With the introduction of the application
gateways, these values are skewed but we get the original values in the
X-Original-XX and X-Forwarded-XX headers. The app just needs to update its
middleware to make use of these applications.
For example:
public void Configure(IApplicationBuilder app)
{
app.UseForwardedHeaders();
app.Use(...);
}
The above works the same as setting a few options directly
in various languages:
- options.ForwardedHeaders = ForwardedHeaders.All;
- options.ForwardedHostHeaderName =
"X-Original-Host";
- options.ForwardLimit = 2;
The number 2 here signifies the hops between the client and
the gateway and the gateway and the app service.
Another alternative is for the Application to specify the
Location Uri to directly include the gateway endpoint. For example:
using System.Net;
using System.Net.Http;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using
Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult>
Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger
function processed a request.");
string gateway =
“gwy-demo-3.centralus.cloudapp.net”;
string name = req.Query["name"];
string requestBody = await new
StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function
executed successfully. Pass a name in the query string or in the request body
for a personalized response."
: $"Hello, {name}. This HTTP triggered
function executed successfully for a request that came from: {req.Headers.Host}.";
var result = new AcceptedResult($"https://{gateway}/", responseMessage);
return result;
}
Finally, there is a conditional
rewrite rule that we can author on the application gateway as an alternative to
fixing all the responses from all the applications that are backend pool
members of the application gateway.
Sample deployment: gwy3proof.zip
Reference: Article on how to
author rewrite rules.
No comments:
Post a Comment