Custom Authorization in Azure Functions v4 with .NET 7 isolated

880 views Asked by At

I'm attempting to implement custom authorization in Azure Functions v4 using .NET 7 isolated process. Previously, there was the FunctionExecutingContext which could be used with attributes to handle custom authorization logic, but it's now marked as obsolete.

// Sample of the old approach
public sealed class AuthorizeAttribute : FunctionInvocationFilterAttribute
{
   public override void OnExecuting(FunctionExecutingContext executingContext)
   {
       // ... logic here ...
   }
}

With this no longer being recommended, what's the new way of handling this in Azure Functions v4 with .NET 6 isolated?

Any guidance or sample implementations would be greatly appreciated!

2

There are 2 answers

0
SiddheshDesai On

Instead of using FunctionExecutingContext, you can utilise FunctionContext in Azure Functions v4 with a.NET 7 isolated process to manage specific authorization.

The HttpRequestData object, which holds the HTTP request information for the currently invoked function, is accessible through the FunctionContext class. To add unique permission logic to your function code, utilise this object.

Reference1 and Document to get started with .Net 7 Isolate Functions

Sample Http Function code in .Net 7 Isolated framework:-

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace FunctionApp44
{
    public class Function1
    {
        private readonly ILogger _logger;

        public Function1(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<Function1>();
        }

        [Function("Function1")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executioncontext)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Welcome to Azure Functions!");

            return response;
        }
    }
}

enter image description here

enter image description here

0
Arturo Martinez On

Take a look at DarkLoop.Azure.Functions.Authorization.Isolated

You configure your functions app just like any other asp.net core application and make use of AuthorizeAttribute or AllowAnonymousAttribute to control access. This framework makes use of all the infrastructure already in ASP.NET core.

Your Isolated functions need to be running in ASP.NET Core integration mode for this package to work.

Here is a post explaining how it works.