Test Your Azure Function Http Trigger Authorization Levels
If you are using HTTP trigger bindings and are relying on keys to secure them using AuthorizationLevel.Function
,
you might want a way verify that you haven’t accidentally left one of them exposed
as AuthorizationLevel.Anonymous
.
With a bit of reflection you can accomplish this in a unit test (I’m using the excellent xUnit and FluentAssertions here):
1[Fact]
2public void AllHttpTriggerFunctions_MustHaveFunctionSecurity()
3{
4 // Get the assembly containing the Azure Functions
5 var types = typeof(Startup).Assembly.GetTypes();
6
7 // Find all the HttpTriggerAttributes associated to any method in any of the types
8 // in the assembly
9 var httpTriggerAttributes = types
10 .SelectMany(t => t
11 .GetMethods()
12 .Select(m => m.GetParameters()
13 .Select(p => p.GetCustomAttribute<HttpTriggerAttribute>()).FirstOrDefault()))
14 .Where(p => p != null)
15 .ToList();
16
17 httpTriggerAttributes.Should().NotBeEmpty();
18
19 foreach (var httpTrigger in httpTriggerAttributes)
20 {
21 httpTrigger.AuthLevel.Should().Be(AuthorizationLevel.Function);
22 }
23}
That’s it. Now it’s even harder to make a mistake, which is a good thing.