twilio-labs / twilio-aspnet

Integrate Twilio Programmable Messaging and Voice with ASP.NET Respond to webhooks with TwiML in seconds
Apache License 2.0
59 stars 30 forks source link

Use Forwarded headers for request validation when available #111

Closed Swimburger closed 1 year ago

Swimburger commented 1 year ago

When in front of a reverse proxy or a tunnel like ngrok, we currently have to set the BaseUrlOverride setting, but we could make skip this extra step if the request validation helper would take the Forwarded headers into consideration.

There are many of these headers, so we'd need to figure out which to use and not to use.

Not having to update the BaseUrlOverride anytime we restart ngrok would be a great improvement to the developer experience.

Swimburger commented 1 year ago

This is quite amazing, ASP.NET Core has built-in middleware that will use the forwarding headers to configure the current request with those properties. So the Twilio.AspNet.Core library doesn't have to do anything to add support for this, it just works.

Here's an example:

using Microsoft.AspNetCore.HttpOverrides;
using Twilio.AspNet.Core;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTwilioRequestValidation();

builder.Services.Configure<ForwardedHeadersOptions>(options => options.ForwardedHeaders = ForwardedHeaders.All);

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseForwardedHeaders();

// use your MVC, endpoints, etc.

app.Run();

By configuring ForwardedHeadersOptions and using the app.UseForwardedHeaders() middleware, the Twilio request validation will validate the correct URL, without the need for BaseUrlOverride. This works with ngrok and other reverse proxies. You can learn more about the forwarded headers feature at Microsoft docs, and this includes important security considerations!

If you do use BaseUrlOverride, the override will be used instead of the forwarded headers.