How to use Azure Function filtering with FunctionInvocationFilterAttribute in .Net 5

Viewed 3028

According to this article, Azure Functions can have an attribute that is triggered by the execution of the function:

internal class AuthorizeAttribute : FunctionInvocationFilterAttribute
{
    public override async Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken)
    {
        var request = (HttpRequest)executingContext.Arguments["req"];
        var user = await AuthorizationHandler.ValidateRequestAsync(request, executingContext.Logger);

        if (user != null)
        {
            request.HttpContext.User.AddIdentities(user.Identities);
        }
        else
        {
            request.HttpContext.Response.StatusCode = 401;
            await request.HttpContext.Response.Body.FlushAsync();
            request.HttpContext.Response.Body.Close();
    

    throw new UnauthorizedException();
    }
}



[Authorize]
[FunctionName("SampleFunction")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "sample")] HttpRequest req,
    ILogger log, ClaimsPrincipal user)
{
  ...
}

This could allow us to create some security check before the function is executed.

Unfortunately all the examples are for Azure Functions v1-v3 and uses a different syntax.

The new Functions syntax is somewhat different:

[Authorize]
[Function("GetData")]
public async Task<HttpResponseData> GetData(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "data1")] HttpRequestData req,
     FunctionContext executionContext, ClaimsPrincipal claimsPrincipal)
{
  ...
}

Using Microsoft.Azure.Functions.Worker functions, the attribute is not triggered.

Can you give me some hint of how to modify the code to create a pre-execution check?

1 Answers

Thank you user1672994. Posting your suggestions as an answer to help other community members.

.NET isolated also supports middleware registration, again by using a model similar to what exists in ASP.NET.

The ConfigureFunctionsWorkerDefaults extension method has an overload that lets you register your own middleware.

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(workerApplication =>
    {
        // Register our custom middleware with the worker
        workerApplication.UseMiddleware<MyCustomMiddleware>();
    })
    .Build();
Related