Slicc
Slicc

Reputation: 3435

Custom authorisation of an Azure Function

I've set up my Azure Function and I can see that there are options to support Azure Active Directory for authentication, which looks great. In a previous project I have used .NET Core to host a WebAPI and subsequently used Authorisation Policies (https://learn.microsoft.com/en-us/aspnet/core/security/authorization/) to provide fine grained claims based authorisation in my API. I cannot seem to find an equivalent mechanism in an Azure Function.

Can anyone tell me if there is a way to do this sort of thing in an Azure Function?

Upvotes: 1

Views: 2034

Answers (1)

mattchenderson
mattchenderson

Reputation: 1620

There is not currently built-in support for fine-grained authorization. This would make a great suggestion item for the Functions UserVoice.

You could always write authorization logic as a part of your function, although a built-in feature would certainly be better. The below code snippet (C#) does an authentication check in code and prints a list of claims. You could modify it to require specific claims:

using System.Net;
using System.Threading;
using System.Security.Claims;
 
public static void Run(HttpRequestMessage req, TraceWriter log)
{
    if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
    {
        log.Info("Not authenticated");
        return req.CreateResponse(HttpStatusCode.Unauthorized);
    }
    
    ClaimsIdentity identity = (Thread.CurrentPrincipal as ClaimsPrincipal)?.Identity as ClaimsIdentity;
    if (identity != null) 
       {
        foreach (var claim in identity.Claims)
        {
           log.Info($"{claim.Type} = {claim.Value}");
        }
    }

    // Rest of your function...

    return req.CreateResponse(HttpStatusCode.OK);
}

Note that in non-.NET languages, you would want to inspect the headers for claims information. You could also combine this with calls to the /.auth/me endpoint and provider graph endpoints.

Upvotes: 4

Related Questions