Group role based authorization

257 views Asked by At

I've been trying to implement a group based authorization. I have gone ahead and implemented the user based authorization using the content below: https://medium.com/medialesson/role-based-authorization-in-azure-functions-with-azure-ad-and-app-roles-b1fed5714c91

Using this content, does anyone know how to change my code, so it is able to handle groups, not roles? I went ahead and changed the manifest in Azure to include securitygroups. Any help would be appreciated. Below is the code:

internal class RoleAuthorizeAttribute : FunctionInvocationFilterAttribute
{
    ...

    public override async Task OnExecutingAsync(FunctionExecutingContext executingContext, CancellationToken cancellationToken)
    {
        if (!executingContext.Arguments.ContainsKey("principal"))
        {
            throw new AuthorizationException("Authentication failed. Missing claims.");
        }

        var claimsPrincipal = (ClaimsPrincipal)executingContext.Arguments["principal"];
        var roles = claimsPrincipal.Claims.Where(e => e.Type == "roles").Select(e => e.Value);

        var isMember = roles.Intersect(_validRoles).Count() > 0;
        if (!isMember)
        {
            throw new AuthorizationException("Authentication failed. User not assigned to one of the required roles.");
        }
    }
}
1

There are 1 answers

0
Allen Wu On

Use claimsPrincipal.Claims.Where(e => e.Type == "groups") to get the groups claim.

The groups claim only returns group id rather than group name. You can loop the group ids to use Microsoft Graph to query the group names: var group = await graphClient.Groups[{group id}"].Request().GetAsync();. Then you could match them against the group attributes you set.

See Microsoft Graph reference here.