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

Add ValidateTwilioRequestFilter #97

Closed Swimburger closed 2 years ago

Swimburger commented 2 years ago

This feature is for .NET 7 only. It add the ValidateTwilioRequestFilter which can be used to verify HTTP request originated from Twilio in Minimal APIs.

Usage:

using Twilio.AspNet.Core;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTwilioRequestValidation();

var app = builder.Build();

app.MapPost("/sms", () => ...)
    .ValidateTwilioRequest();

app.Run();

You can also apply this to a group:

var twilioGroup = app.MapGroup("/twilio");
twilioGroup.ValidateTwilioRequest();
{
    twilioGroup.MapPost("/sms", () => ...);
    twilioGroup.MapPost("/voice", () => ...);
}

Alternatively, you can add the ValidateTwilioRequestFilter filter yourself instead of using the .ValidateTwilioRequest extension method:

app.MapPost("/sms", () => ...)
    .AddEndpointFilter<ValidateTwilioRequestFilter>();

Before using the ValidateTwilioRequestFilter, you have to configure request validation using builder.Services.AddTwilioRequestValidation();.

This PR also contains some extra unit tests for the ValidateRequest attribute. Lastly, dotnet6.csproj has been renamed to AspNetCore.csproj.

Contributing to Twilio

All third-party contributors acknowledge that any contributions they provide will be made under the same open-source license that the open-source project is provided under.

Swimburger commented 2 years ago

We'll have to wait until .NET 7 is released in November to build it in CI.

Swimburger commented 2 years ago

This is a breaking change which I can revert, but I made the RequestValidationHelpers static since they are pure functions and the class doesn't store any instance data.