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?