Showing posts with label .NET 8. Show all posts
Showing posts with label .NET 8. Show all posts

Saturday, 24 January 2026

Avoiding the Pitfalls of Stopping Permission Inheritance: Performance Hotspots, Safer Patterns, and Azure-First Remediation

Stopping inherit permission (i.e., breaking permission inheritance) often seems like a quick fix for access control, but it introduces hidden operational and performance costs. This article explains why breaking inheritance in SharePoint and Azure RBAC leads to complexity, where performance issues occur, and how to remediate with .NET 8, TypeScript, and Azure-first patterns using Managed Identities and Infrastructure as Code.

The Problem

Breaking inheritance creates many one-off permission entries. Over time, this causes:

  • Permission sprawl: hard-to-audit, hard-to-revoke access scattered across items/resources.
  • Performance degradation: larger ACL evaluations, slower queries, and increased throttling risk.
  • Operational friction: brittle reviews, noisy exceptions, and confusing user experiences.

In SharePoint, many uniquely permissioned items slow list queries and complicate sharing. In Azure, assigning roles at leaf scopes (instead of using inherited assignments at management group or subscription levels) increases evaluation overhead and management burden.

Prerequisites

  • .NET 8 SDK
  • Node.js v20+
  • Azure CLI (az) and Azure Bicep
  • Contributor access to a test subscription (for deploying IaC) and Reader/Authorization permissions for audit scenarios

The Solution (Step-by-Step)

Step 1: What to avoid when stopping inheritance

  • SharePoint: Avoid per-item unique permissions for large lists; prefer groups at the site or library level, with exceptions gated by policy and approval.
  • Azure RBAC: Avoid many role assignments at the resource/resource-group level; grant least privilege at a higher scope when practical, and use groups instead of direct user assignments.

Step 2: .NET 8 Minimal API to detect RBAC hotspots (top-level statements, DI, Managed Identity)

// File: Program.cs (.NET 8, top-level statements, minimal API)
// Purpose: Audit Azure RBAC for non-inherited, leaf-level role assignments (hotspots).
// Auth: Uses DefaultAzureCredential (Managed Identity preferred in Azure).
// Note: This sample reads role assignments and surfaces "leaf" hotspots for review.

using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Authorization;
using Azure.ResourceManager.Authorization.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Register Azure clients via DI
builder.Services.AddSingleton<TokenCredential>(_ => new DefaultAzureCredential());
// ArmClient is the entry point to Resource Manager APIs
builder.Services.AddSingleton<ArmClient>(sp => new ArmClient(sp.GetRequiredService<TokenCredential>()));

var app = builder.Build();

// GET /rbac/hotspots?subscriptionId=<subId>
// Heuristic: Identify role assignments at deeper scopes (resource, resource group) that
// could be consolidated at higher scopes to reduce sprawl and evaluation overhead.
app.MapGet("/rbac/hotspots", async (string subscriptionId, ArmClient arm) =>
{
    // Acquire subscription resource
    var sub = arm.GetSubscriptionResource(new ResourceIdentifier($"/subscriptions/{subscriptionId}"));

    // List role assignments across the subscription
    var assignments = new List<RoleAssignmentData>();
    await foreach (var ra in sub.GetRoleAssignmentsAsync())
    {
        assignments.Add(ra.Data);
    }

    // Group by scope depth (subscription=1, resourceGroup=2, resource=3+)
    // Deeper scopes are more likely to be "breaks" from inheritance-like patterns.
    var hotspots = assignments
        .GroupBy(a => ScopeDepth(a.Scope))
        .OrderByDescending(g => g.Key)
        .Select(g => new
        {
            depth = g.Key,
            count = g.Count(),
            sampleScopes = g.Select(x => x.Scope).Distinct().Take(5).ToArray()
        });

    return Results.Ok(new
    {
        analyzed = assignments.Count,
        hotspots
    });

    // Simple helper to score scope depth by path segments.
    static int ScopeDepth(string scope)
    {
        // Example: /subscriptions/{id} => depth ~ 1
        // /subscriptions/{id}/resourceGroups/{rg} => depth ~ 2
        // /subscriptions/{id}/resourceGroups/{rg}/providers/... => depth >= 3
        return scope.Split('/', StringSplitOptions.RemoveEmptyEntries).Length / 2;
    }
})
.WithName("GetRbacHotspots")
.Produces<object>(200);

app.Run();

Why this helps: Large counts of deep-scope assignments often indicate broken inheritance patterns (per-resource grants). Consolidating to group-based roles at higher scopes can reduce policy evaluation work and administrative overhead.

Step 3: TypeScript Azure Function to list deep-scope role assignments with retry (Managed Identity)

// File: index.ts (Azure Functions v4, Node 20)
// Purpose: Enumerate role assignments and flag deep-scope patterns.
// Auth: ManagedIdentityCredential (no client secrets). Strict typing. Basic retry for 429.
//
// Ensure you enable a system-assigned identity on the Function App and grant it Reader on the subscription.
// package.json should include: @azure/identity, @azure/arm-authorization, zod

import { AzureFunction, Context } from "@azure/functions";
import { ManagedIdentityCredential } from "@azure/identity";
import { AuthorizationManagementClient, RoleAssignment } from "@azure/arm-authorization";
import { z } from "zod";

// Validate required environment variable via Zod (strict typing)
const EnvSchema = z.object({
  SUBSCRIPTION_ID: z.string().min(1)
});
const env = EnvSchema.parse(process.env);

const httpTrigger: AzureFunction = async function (context: Context): Promise<void> {
  // Create credential using Managed Identity (no secrets in code or env)
  const credential = new ManagedIdentityCredential();
  const authClient = new AuthorizationManagementClient(credential, env.SUBSCRIPTION_ID);

  // Simple retry wrapper for throttle-prone calls (e.g., large tenants)
  async function withRetry<T>(fn: () => Promise<T>, attempts = 5, delayMs = 1000): Promise<T> {
    let lastErr: unknown;
    for (let i = 0; i < attempts; i++) {
      try {
        return await fn();
      } catch (err: unknown) {
        const anyErr = err as { statusCode?: number };
        if (anyErr?.statusCode === 429 || anyErr?.statusCode === 503) {
          await new Promise((r) => setTimeout(r, delayMs * (i + 1))); // Exponential-ish backoff
          lastErr = err;
          continue;
        }
        throw err;
      }
    }
    throw lastErr;
  }

  // List role assignments at subscription scope
  const scope = `/subscriptions/${env.SUBSCRIPTION_ID}`;
  const assignments: RoleAssignment[] = [];

  // Use retry around list calls; the SDK returns an async iterator
  const pager = authClient.roleAssignments.listForSubscription();
  for await (const item of pager) {
    assignments.push(item);
  }

  // Score depth by scope path complexity
  const scoreDepth = (s: string): number => s.split("/").filter(Boolean).length / 2;
  const hotspots = assignments
    .map(a => ({ id: a.id!, scope: a.scope!, depth: scoreDepth(a.scope!) }))
    .filter(x => x.depth >= 3); // resource-level assignments

  context.res = {
    status: 200,
    headers: { "content-type": "application/json" },
    body: {
      analyzed: assignments.length,
      resourceLevelAssignments: hotspots.length,
      hotspotSamples: hotspots.slice(0, 10)
    }
  };
};

export default httpTrigger;

Why this helps: A quick serverless audit allows teams to discover where inheritance-like patterns are being bypassed in Azure RBAC, which is a frequent source of performance and governance friction.

Step 4: Azure Bicep to deploy a Function App with Managed Identity and least privilege

// File: main.bicep
// Purpose: Deploy a Function App with system-assigned managed identity,
// and assign Reader at the resource group scope (principle of least privilege).
// Includes a deterministic GUID for role assignment name.
//
// Note: Reader role definition ID is acdd72a7-3385-48ef-bd42-f606fba81ae7
// (Allows viewing resources, not making changes.)

@description('Location for resources')
param location string = resourceGroup().location

@description('Function App name')
param functionAppName string

@description('Storage account name (must be globally unique)')
param storageAccountName string

var roleDefinitionIdReader = '/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7'

// Storage (for Functions)
resource stg 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
  properties: {
    allowBlobPublicAccess: false
    minimumTlsVersion: 'TLS1_2'
    supportsHttpsTrafficOnly: true
  }
}

// Hosting plan (Consumption)
resource plan 'Microsoft.Web/serverfarms@2022-09-01' = {
  name: '${functionAppName}-plan'
  location: location
  sku: {
    name: 'Y1'
    tier: 'Dynamic'
  }
}

// Function App with system-assigned identity
resource func 'Microsoft.Web/sites@2022-09-01' = {
  name: functionAppName
  location: location
  kind: 'functionapp'
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    serverFarmId: plan.id
    siteConfig: {
      appSettings: [
        { name: 'FUNCTIONS_WORKER_RUNTIME', value: 'node' }
        { name: 'WEBSITE_RUN_FROM_PACKAGE', value: '1' }
      ]
    }
  }
}

// Assign Reader at the resource group scope to the Function's identity
// Use a stable, deterministic GUID based on scope + principal to avoid duplicates.
resource readerAssign 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(resourceGroup().id, func.identity.principalId, roleDefinitionIdReader)
  scope: resourceGroup()
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
    principalId: func.identity.principalId
    principalType: 'ServicePrincipal'
  }
}

Why this helps: You deploy secure defaults and enforce least privilege by design. The deterministic GUID prevents accidental duplicate role assignments. Reader is explicitly chosen to avoid write permissions while enabling inventory and audits.

Where performance issues occur

  • SharePoint: Many items with unique permissions increase ACL checks and can slow list queries, indexing, and certain sharing operations. Batch operations on items with unique permissions are more likely to hit throttling.
  • Azure RBAC: Thousands of per-resource role assignments increase evaluation work during authorization and complicate policy and compliance scans. It also prolongs investigations during incidents.
  • Auditing and reviews: Per-user, per-resource assignments inflate review surfaces and make access recertification slow and error-prone.

Best Practices & Security

  • Use Managed Identity or Azure AD Workload Identity. Avoid client secrets for server-side workloads. Do not store secrets in environment variables. If you must handle secrets, use Azure Key Vault with RBAC and Managed Identity.
  • Prefer group-based assignments over direct user assignments. This simplifies reviews and minimizes churn.
  • Favor higher-scope role assignments with least privilege. Start at management group or subscription only when justified and narrow to Reader or custom roles that fit the minimal required actions.
  • When exceptions are necessary, document them. Add expiration and owners to each exception.
  • For SharePoint, grant permissions at the site or library level using groups. Reserve item-level breaks for rare, time-bound cases.
  • Monitor continuously. Integrate with Azure Monitor and Azure Policy to detect excessive deep-scope assignments. Create alerts on abnormal growth of role assignments or access anomalies.
  • Implement retry and backoff for API calls that can throttle (429/503), both in audits and operational tooling.
  • Standardize terminology. Use "inheritance" consistently to avoid confusion in documentation and automation.

Recommendation: If you need read-only inventory across a subscription, assign the Reader role (roleDefinitionId acdd72a7-3385-48ef-bd42-f606fba81ae7) to a Managed Identity and call Azure SDKs or ARM REST with exponential backoff.

Summary

  • Breaking inheritance increases complexity and can degrade performance; reserve it for rare, time-bound exceptions.
  • Automate audits with Managed Identity using .NET 8 and TypeScript to find deep-scope hotspots and consolidate access.
  • Ship secure-by-default with Bicep: least privilege (Reader), deterministic role assignment IDs, and continuous monitoring via Azure services.

Configuring Permission in SharePoint with .NET 8 and Microsoft Graph (Azure-first)

If you need to automate permission in SharePoint reliably, use Microsoft Graph with .NET 8 and Azure-managed identities. The goal: grant site-scoped access (least privilege via Sites.Selected), verify effective roles, and perform read/write operations without client secrets.

The Problem

SharePoint permissions are often over-provisioned or managed manually. That leads to audit gaps, break-glass patterns, and production drift. You need a repeatable, least-privilege approach that grants only the required access to specific sites, automates verification, and avoids client secrets.

Prerequisites

Required tools and permissions:

  • .NET 8 SDK
  • Azure CLI v2.58+ (logged in as a tenant admin for one-time grants)
  • Microsoft Graph application permissions consent capability (tenant admin)
  • Azure subscription access to create a user-assigned managed identity (Contributor on resource group)

The Solution (Step-by-Step)

Step 1. Choose the authentication model

Use managed identity for workloads in Azure (Functions, Container Apps). This removes client secrets entirely. For CI/CD, use workload identity federation instead of secrets.

  • Runtime principal: user-assigned/system-assigned managed identity
  • Graph permission model: application permission Sites.Selected for the runtime principal
  • Grant site-scoped roles: read or write at the specific SharePoint site level

Why Sites.Selected: it blocks blanket access (e.g., Sites.Read.All) and forces explicit grants per site.

Step 2. Infrastructure as Code (Bicep): create a user-assigned managed identity

// main.bicep
targetScope = 'resourceGroup'

// User-assigned managed identity that will call Microsoft Graph
resource uami 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
  name: 'sp-sites-selected-uami'
  location: resourceGroup().location
}

output uamiClientId string = uami.properties.clientId
output uamiPrincipalId string = uami.properties.principalId

After deployment, assign Microsoft Graph application permission Sites.Selected to the managed identity’s service principal. This is a one-time admin action.

# Assign Graph app role (Sites.Selected) to the managed identity service principal
# 1) Get Graph service principal (well-known)
GRAPH_SP_ID=$(az ad sp list --filter "appId eq '00000003-0000-0000-c000-000000000000'" --query "[0].id" -o tsv)

# 2) Get the Sites.Selected app role ID
SITES_SELECTED_ROLE_ID=$(az ad sp show --id $GRAPH_SP_ID --query "appRoles[?value=='Sites.Selected' && allowedMemberTypes[@]=='Application'].id" -o tsv)

# 3) Get your managed identity's service principal object id
UAMI_PRINCIPAL_ID=<uamiPrincipalId from bicep output>

# 4) Assign the app role to the managed identity
az ad sp add-approle-assignment \
  --id $UAMI_PRINCIPAL_ID \
  --principal-object-id $UAMI_PRINCIPAL_ID \
  --resource-id $GRAPH_SP_ID \
  --app-role-id $SITES_SELECTED_ROLE_ID

Admin consent is implicit when you add an app role assignment to Graph for an enterprise application (service principal). Validate in Entra ID under Enterprise applications > Your Managed Identity > Permissions.

Step 3. One-time site-scoped grant to the managed identity

Sites.Selected requires a per-site grant. Use an admin-only tool to grant read/write on a single site to the managed identity. Below is a .NET 8 minimal API you can run locally as a tenant admin via Azure CLI authentication to grant permissions. It uses DI, file-scoped namespaces, and the Microsoft Graph SDK.

using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Kiota.Abstractions.Authentication;

namespace SharePointPermAdmin;

var builder = WebApplication.CreateBuilder(args);

// Admin credential for local, one-time operations only.
// Uses Azure CLI token of a tenant admin. No client secrets.
builder.Services.AddSingleton((sp) =>
{
    // Authenticate as the signed-in Azure CLI account
    var credential = new AzureCliCredential();

    // Adapter for Microsoft Graph SDK
    var authProvider = new TokenCredentialAuthenticationProvider(
        credential,
        // Microsoft Graph default scope for app-permission endpoints
        new[] { "https://graph.microsoft.com/.default" });

    return new GraphServiceClient(authProvider);
});

var app = builder.Build();

// Code Overview: Grants site-level permission (read or write) to a target application or managed identity
// Endpoint parameters:
//  - hostname: e.g., "contoso.sharepoint.com"
//  - sitePath: e.g., "/sites/Engineering"
//  - targetAppId: the clientId of the target app or managed identity (UAMI clientId)
//  - role: "read" or "write" (least privilege)
app.MapPost("/grant", async (GraphServiceClient graph,
    string hostname, string sitePath, string targetAppId, string role) =>
{
    // 1) Resolve the site by hostname and site path
    var site = await graph.Sites["{hostname}:{sitePath}"].GetAsync();
    if (site is null) return Results.NotFound("Site not found.");

    // 2) Prepare the permission grant
    var requestedRole = role.Equals("write", StringComparison.OrdinalIgnoreCase) ? "write" : "read";

    var permission = new Permission
    {
        // Roles supported for Sites.Selected are "read" and "write"
        Roles = new List<string> { requestedRole },
        GrantedToIdentities = new List<IdentitySet>
        {
            new IdentitySet
            {
                Application = new Identity
                {
                    // targetAppId can be the clientId of a user-assigned managed identity
                    // or an app registration clientId
                    Id = targetAppId,
                    DisplayName = "Sites.Selected App"
                }
            }
        }
    };

    // 3) Grant the permission at the site-level
    var created = await graph.Sites[site.Id].Permissions.PostAsync(permission);

    // 4) Return what was granted for audit
    return Results.Ok(new
    {
        SiteId = site.Id,
        GrantedRoles = created?.Roles,
        GrantedTo = created?.GrantedToIdentities?.Select(x => x.Application?.Id)
    });
});

app.Run();

Run this locally with an Azure CLI context that has tenant admin privileges. This API grants the site-scoped role to your managed identity (identified by its clientId). Keep this tool restricted and audit its use.

Step 4. Runtime workload: access the site using the managed identity

Your production service (Azure Functions or Container Apps) uses DefaultAzureCredential to get a token for Graph and perform read actions (if granted read) or write actions (if granted write).

using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Graph;
using Microsoft.Kiota.Abstractions.Authentication;

namespace SharePointRuntime;

var builder = WebApplication.CreateBuilder(args);

// Graph client using managed identity in Azure (no secrets)
// In local dev, DefaultAzureCredential falls back to Azure CLI login.
builder.Services.AddSingleton((sp) =>
{
    var credential = new DefaultAzureCredential();
    var authProvider = new TokenCredentialAuthenticationProvider(
        credential,
        new[] { "https://graph.microsoft.com/.default" });

    return new GraphServiceClient(authProvider);
});

var app = builder.Build();

// Code Overview: Example read-only endpoint listing drive root items for a given site.
// Requires the managed identity to have Sites.Selected + "read" on that site.
app.MapGet("/sites/{hostname}/{*sitePath}/drive-items", async (GraphServiceClient graph, string hostname, string sitePath) =>
{
    // 1) Resolve site by hostname and site path
    var site = await graph.Sites[$"{hostname}:{sitePath}"].GetAsync();
    if (site is null) return Results.NotFound("Site not found.");

    // 2) Read drive root items (read permission is sufficient)
    var items = await graph.Sites[site.Id].Drive.Root.Children.GetAsync();

    return Results.Ok(items?.Value?.Select(i => new { i.Id, i.Name, i.Size, i.LastModifiedDateTime }));
});

app.Run();

Step 5. Optional: strict front-end validation for an internal admin form

If you build an admin UI to call the grant API, validate inputs with Zod and strict TypeScript types.

import { z } from 'zod';

// Discriminated union for role
const RoleSchema = z.union([z.literal('read'), z.literal('write')]);

// Strict payload schema
export const GrantPayloadSchema = z.object({
  hostname: z.string().min(1).regex(/^([a-zA-Z0-9-]+)\.sharepoint\.com$/),
  sitePath: z.string().min(1).startsWith('/'),
  targetAppId: z.string().uuid(),
  role: RoleSchema
});

export type GrantPayload = z.infer<typeof GrantPayloadSchema>;

// Example safe submit
export async function submitGrant(payload: GrantPayload) {
  const parsed = GrantPayloadSchema.parse(payload); // throws on invalid input
  const res = await fetch('/grant?'
    + new URLSearchParams({
      hostname: parsed.hostname,
      sitePath: parsed.sitePath,
      targetAppId: parsed.targetAppId,
      role: parsed.role
    }), { method: 'POST' });

  if (!res.ok) throw new Error('Grant failed');
  return res.json();
}

Best Practices & Security

  • Best Practice: Use Sites.Selected and grant per-site roles (read/write) instead of tenant-wide Sites.Read.All or Sites.FullControl.All.
  • Best Practice: Prefer managed identity (Azure) or workload identity federation (CI/CD) over client secrets.
  • Best Practice: Separate duties. Keep the grant tool under tenant admin control; the runtime app should never be able to self-elevate.
  • Best Practice: Log every permission grant with who, what, when, and siteId. Store in an immutable audit store.
  • Best Practice: Implement retries with exponential backoff for Graph calls and handle 429/5xx responses gracefully.
  • Best Practice: Validate all inputs server-side. Reject unknown hostnames and unexpected site paths.
  • Best Practice: Monitor with Microsoft 365 audit logs and alert on unexpected grants or role changes.

Minimum permissions required (explicit)

  • Runtime principal (managed identity): Microsoft Graph application permission Sites.Selected.
  • Admin/grant principal: Microsoft Graph application permission Sites.FullControl.All or delegated SharePoint admin role sufficient to create site-level grants via Graph.
  • SharePoint site roles used for Sites.Selected: read (equivalent to site Read), write (equivalent to Edit). Grant the lowest role that satisfies requirements.

Error handling notes

  • Catch GraphServiceException and map common statuses: 403 (insufficient role), 404 (site not found), 429 (throttle) with Retry-After.
  • Add circuit breakers/timeouts. Do not leak raw exception messages in responses.
  • Return correlation IDs in responses to aid troubleshooting.

Summary

  • Grant permission in SharePoint using Sites.Selected for least privilege and auditability.
  • Use managed identities or workload identity federation to remove secrets and simplify compliance.
  • Automate grants and access with .NET 8, Microsoft Graph SDK, and IaC for consistent, repeatable operations.

Sunday, 18 January 2026

Integrate Power Apps with AI using Azure Functions (.NET 8) and Azure OpenAI with Managed Identity

Integrate Power Apps with AI by fronting Azure OpenAI behind a secure .NET 8 isolated Azure Function, authenticated via Entra ID and deployed with Azure Bicep. Why this matters: you keep your Azure OpenAI keyless via Managed Identity, enforce RBAC, and provide a stable HTTPS endpoint for Power Apps using a custom connector.

The Problem

Developers need to call AI securely from Power Apps without exposing keys, while meeting enterprise requirements for RBAC, observability, and least-privilege. Manual wiring through the portal and ad hoc security checks lead to drift and risk.

Prerequisites

  • Azure CLI 2.60+
  • .NET 8 SDK
  • Azure Developer CLI (optional) or Bicep CLI
  • Owner or User Access Administrator on the target subscription
  • Power Apps environment access for creating a custom connector

The Solution (Step-by-Step)

1) Deploy Azure resources with Bicep (Managed Identity, Function App, Azure OpenAI, RBAC, Easy Auth)

This Bicep template creates a Function App with system-assigned managed identity, Azure OpenAI with a model deployment, App Service Authentication (Easy Auth) enforced, and assigns the Cognitive Services OpenAI User role to the identity.

// main.bicep
targetScope = 'resourceGroup'

@description('Name prefix for resources')
param namePrefix string

@description('Location for resources')
param location string = resourceGroup().location

@description('Azure OpenAI model name, e.g., gpt-4o-mini')
param aoaiModelName string = 'gpt-4o-mini'

@description('Azure OpenAI model version for your region (see Azure docs for supported versions).')
param aoaiModelVersion string = '2024-07-18' // Tip: Validate the correct version via az cognitiveservices account list-models

var funcName = '${namePrefix}-func'
var aoaiName = '${namePrefix}-aoai'
var hostingPlanName = '${namePrefix}-plan'
var appInsightsName = '${namePrefix}-ai'
var storageName = toLower(replace('${namePrefix}st${uniqueString(resourceGroup().id)}', '-', ''))

resource storage 'Microsoft.Storage/storageAccounts@2023-05-01' = {
  name: storageName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}

resource appInsights 'Microsoft.Insights/components@2020-02-02' = {
  name: appInsightsName
  location: location
  kind: 'web'
  properties: {
    Application_Type: 'web'
  }
}

resource plan 'Microsoft.Web/serverfarms@2023-12-01' = {
  name: hostingPlanName
  location: location
  sku: {
    name: 'Y1' // Consumption for Functions
    tier: 'Dynamic'
  }
}

resource func 'Microsoft.Web/sites@2023-12-01' = {
  name: funcName
  location: location
  kind: 'functionapp'
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    serverFarmId: plan.id
    siteConfig: {
      appSettings: [
        { name: 'AzureWebJobsStorage', value: storage.listKeys().keys[0].value }
        { name: 'APPLICATIONINSIGHTS_CONNECTION_STRING', value: appInsights.properties.ConnectionString }
        { name: 'FUNCTIONS_EXTENSION_VERSION', value: '~4' }
        { name: 'FUNCTIONS_WORKER_RUNTIME', value: 'dotnet-isolated' }
        // Enable Easy Auth enforcement via config below (authSettingsV2)
      ]
      http20Enabled: true
      minimumTlsVersion: '1.2'
      ftpsState: 'Disabled'
      cors: {
        allowedOrigins: [
          // Add your Power Apps domain if needed; CORS is typically managed by the custom connector
        ]
      }
    }
    httpsOnly: true
  }
}

// Enable App Service Authentication (Easy Auth) with Entra ID and enforce authentication.
resource auth 'Microsoft.Web/sites/config@2023-12-01' = {
  name: '${func.name}/authsettingsV2'
  properties: {
    globalValidation: {
      requireAuthentication: true
      unauthenticatedClientAction: 'Return401'
    }
    identityProviders: {
      azureActiveDirectory: {
        enabled: true
        registration: {
          // When omitted, system can use an implicit provider. For enterprise, specify a registered app:
          // Provide clientId and clientSecretSettingName if using a dedicated app registration.
        }
        validation: {
          // Audience (App ID URI or application ID). Power Apps custom connector should request this audience.
          // Replace with your API application ID URI when using a dedicated AAD app registration.
          allowedAudiences: [
            'api://<your-app-id>'
          ]
        }
        login: {
          disableWWWAuthenticate: false
        }
      }
    }
    platform: {
      enabled: true
      runtimeVersion: '~1'
    }
    login: {
      tokenStore: {
        enabled: true
      }
    }
  }
}

// Azure OpenAI account
resource aoai 'Microsoft.CognitiveServices/accounts@2023-05-01' = {
  name: aoaiName
  location: location
  kind: 'OpenAI'
  sku: {
    name: 'S0'
  }
  properties: {
    customSubDomainName: toLower(aoaiName)
    publicNetworkAccess: 'Enabled'
  }
}

// Azure OpenAI deployment - ensure model/version are valid for your region
resource aoaiDeployment 'Microsoft.CognitiveServices/accounts/deployments@2023-05-01' = {
  name: 'chat-${aoaiModelName}'
  parent: aoai
  properties: {
    model: {
      format: 'OpenAI'
      name: aoaiModelName
      version: aoaiModelVersion
    }
    capacities: [
      {
        capacity: 1
        capacityType: 'Standard'
      }
    ]
  }
}

// Assign RBAC: Cognitive Services OpenAI User role to the Function's managed identity
// Built-in role: Cognitive Services OpenAI User (Role ID: 5e0bd9bd-7ac1-4c9e-8289-1b01f135d4a8)
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(aoai.id, func.identity.principalId, 'CognitiveServicesOpenAIUserRole')
  scope: aoai
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '5e0bd9bd-7ac1-4c9e-8289-1b01f135d4a8')
    principalId: func.identity.principalId
    principalType: 'ServicePrincipal'
  }
}

output functionAppName string = func.name
output openAiEndpoint string = 'https://${aoai.name}.openai.azure.com/'
output openAiDeployment string = aoaiDeployment.name

Tip: To find the correct model version for your region, run: az cognitiveservices account list-models --name <aoaiName> --resource-group <rg> --output table.

2) Implement a secure .NET 8 isolated Azure Function with DI and Managed Identity

The function validates Entra ID via Easy Auth headers, performs input validation, calls Azure OpenAI using DefaultAzureCredential, and returns a minimal response. AuthorizationLevel is Anonymous because App Service Authentication is enforcing auth at the edge; the code still verifies identity defensively.

// Program.cs
using System.Text.Json;
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication(builder =>
    {
        // Add global middleware if needed (e.g., correlation, exception handling)
        builder.UseMiddleware<GlobalExceptionMiddleware>();
    })
    .ConfigureServices((ctx, services) =>
    {
        var config = ctx.Configuration;

        // Bind custom options
        services.Configure<OpenAIOptions>(config.GetSection(OpenAIOptions.SectionName));

        // Register OpenAI client using Managed Identity (no keys)
        services.AddSingleton((sp) =>
        {
            var options = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<OpenAIOptions>>().Value;
            // Use DefaultAzureCredential to leverage Managed Identity in Azure
            var credential = new DefaultAzureCredential();
            return new OpenAIClient(new Uri(options.Endpoint), credential);
        });

        services.AddSingleton<IPromptService, PromptService>();
        services.AddApplicationInsightsTelemetryWorkerService();
    })
    .ConfigureAppConfiguration(config =>
    {
        config.AddEnvironmentVariables();
    })
    .ConfigureLogging(logging =>
    {
        logging.AddConsole();
    })
    .Build();

await host.RunAsync();

file sealed class GlobalExceptionMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            var logger = context.GetLogger<GlobalExceptionMiddleware>();
            logger.LogError(ex, "Unhandled exception");

            // Avoid leaking internals; return generic error with correlation ID
            var invocationId = context.InvocationId;
            var http = await context.GetHttpRequestDataAsync();
            if (http is not null)
            {
                var response = http.CreateResponse(System.Net.HttpStatusCode.InternalServerError);
                await response.WriteStringAsync($"Request failed. CorrelationId: {invocationId}");
                context.GetInvocationResult().Value = response;
            }
        }
    }
}

file sealed class OpenAIOptions
{
    public const string SectionName = "OpenAI";
    public string Endpoint { get; init; } = string.Empty; // e.g., https://<aoaiName>.openai.azure.com/
    public string Deployment { get; init; } = string.Empty; // e.g., chat-gpt-4o-mini
}

// Service abstraction to keep function logic clean
file interface IPromptService
{
    Task<string> CreateChatResponseAsync(string userInput, CancellationToken ct);
}

file sealed class PromptService(OpenAIClient client, Microsoft.Extensions.Options.IOptions<OpenAIOptions> opts, ILogger<PromptService> logger) : IPromptService
{
    private readonly OpenAIClient _client = client;
    private readonly OpenAIOptions _opts = opts.Value;
    private readonly ILogger<PromptService> _logger = logger;

    public async Task<string> CreateChatResponseAsync(string userInput, CancellationToken ct)
    {
        // Basic input trimming and minimal length check
        var prompt = (userInput ?? string.Empty).Trim();
        if (prompt.Length < 3)
        {
            return "Input too short.";
        }

        // Create chat completion with minimal system prompt
        var req = new ChatCompletionsOptions()
        {
            DeploymentName = _opts.Deployment,
            Temperature = 0.2f,
            MaxTokens = 256
        };
        req.Messages.Add(new ChatRequestSystemMessage("You are a concise assistant.")); // Guardrail
        req.Messages.Add(new ChatRequestUserMessage(prompt));

        _logger.LogInformation("Calling Azure OpenAI deployment {Deployment}", _opts.Deployment);

        var resp = await _client.GetChatCompletionsAsync(req, ct);
        var msg = resp.Value.Choices.Count > 0 ? resp.Value.Choices[0].Message.Content[0].Text : "No response.";
        return msg ?? string.Empty;
    }
}
// HttpFunction.cs
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Api;

public sealed class ChatRequest
{
    // Strongly typed DTO for request validation
    public string Prompt { get; init; } = string.Empty;
}

public sealed class ChatFunction(IPromptService promptService, ILogger<ChatFunction> logger) 
{
    // Simple helper to read Easy Auth principal header safely
    private static ClaimsPrincipal? TryGetPrincipal(HttpRequestData req)
    {
        // Easy Auth sets x-ms-client-principal as Base64 JSON
        if (!req.Headers.TryGetValues("x-ms-client-principal", out var values)) return null;
        var b64 = values.FirstOrDefault();
        if (string.IsNullOrWhiteSpace(b64)) return null;

        try
        {
            var json = Encoding.UTF8.GetString(Convert.FromBase64String(b64));
            using var doc = JsonDocument.Parse(json);
            var claims = new List<Claim>();
            if (doc.RootElement.TryGetProperty("claims", out var arr))
            {
                foreach (var c in arr.EnumerateArray())
                {
                    var typ = c.GetProperty("typ").GetString() ?? string.Empty;
                    var val = c.GetProperty("val").GetString() ?? string.Empty;
                    claims.Add(new Claim(typ, val));
                }
            }
            return new ClaimsPrincipal(new ClaimsIdentity(claims, "EasyAuth"));
        }
        catch
        {
            return null;
        }
    }

    [Function("chat")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "chat")] HttpRequestData req,
        FunctionContext context)
    {
        var principal = TryGetPrincipal(req);
        if (principal is null)
        {
            // Defense in depth: App Service auth should already block, but we double-check.
            var unauth = req.CreateResponse(HttpStatusCode.Unauthorized);
            await unauth.WriteStringAsync("Authentication required.");
            return unauth;
        }

        // Basic content-type check and bound read limit
        if (!req.Headers.TryGetValues("Content-Type", out var ct) || !ct.First().Contains("application/json", StringComparison.OrdinalIgnoreCase))
        {
            var bad = req.CreateResponse(HttpStatusCode.BadRequest);
            await bad.WriteStringAsync("Content-Type must be application/json.");
            return bad;
        }

        // Safe body read
        using var reader = new StreamReader(req.Body);
        var body = await reader.ReadToEndAsync();
        ChatRequest? input;
        try
        {
            input = JsonSerializer.Deserialize<ChatRequest>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        }
        catch
        {
            var bad = req.CreateResponse(HttpStatusCode.BadRequest);
            await bad.WriteStringAsync("Invalid JSON.");
            return bad;
        }

        if (input is null || string.IsNullOrWhiteSpace(input.Prompt))
        {
            var bad = req.CreateResponse(HttpStatusCode.BadRequest);
            await bad.WriteStringAsync("Prompt is required.");
            return bad;
        }

        var loggerScope = new Dictionary<string, object> { ["UserObjectId"] = principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value ?? "unknown" };
        using (logger.BeginScope(loggerScope))
        {
            try
            {
                var result = await promptService.CreateChatResponseAsync(input.Prompt, context.CancellationToken);
                var ok = req.CreateResponse(HttpStatusCode.OK);
                await ok.WriteAsJsonAsync(new { response = result });
                return ok;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error generating chat response");
                var err = req.CreateResponse(HttpStatusCode.BadGateway);
                await err.WriteStringAsync("AI request failed. Try again later.");
                return err;
            }
        }
    }
}
// appsettings.json (for local debug)
{
  "OpenAI": {
    "Endpoint": "https://<your-aoai-name>.openai.azure.com/",
    "Deployment": "chat-gpt-4o-mini"
  }
}

Tip: When running locally, ensure you are logged in with Azure CLI (az login) so DefaultAzureCredential can acquire a token. Assign yourself Cognitive Services OpenAI User on the AOAI resource for testing.

3) Enforce Azure AD (Easy Auth) - configuration example

The Bicep above enables Easy Auth and returns 401 for unauthenticated calls. If you maintain settings as JSON, you can also use an ARM style configuration:

// Example snippet (appsettings for site config via ARM/Bicep-style) ensures:
// - requireAuthentication: true
// - allowedAudiences must match the audience used by your client (Power Apps custom connector)
{
  "properties": {
    "authSettingsV2": {
      "platform": { "enabled": true },
      "globalValidation": {
        "requireAuthentication": true,
        "unauthenticatedClientAction": "Return401"
      },
      "identityProviders": {
        "azureActiveDirectory": {
          "enabled": true,
          "validation": {
            "allowedAudiences": [ "api://<your-app-id>" ]
          }
        }
      }
    }
  }
}

Tip: For most enterprise setups, register a dedicated App Registration for the Function API and reference its Application ID URI in allowedAudiences. Keep consent and scopes explicit.

4) Create a Power Apps Custom Connector

  1. In Power Apps, open Solutions and create a new Custom Connector.
  2. Set the Host to your Function URL (e.g., https://<func-name>.azurewebsites.net).
  3. Define the POST /chat operation that accepts a JSON body { "prompt": "..." } and returns { "response": "..." }.
  4. Security: Choose OAuth 2.0 (Azure Active Directory). Set Audience to match allowedAudiences (api://<your-app-id>). Supply Tenant ID and Client ID as provided by your admin.
  5. Test the connector. You should receive HTTP 200 with the AI response. Unauthorized calls return 401.

5) Add client-side validation in Power Apps (Power Fx)

Before invoking the connector, validate inputs in the app to fail fast and reduce server load.

// Example Power Fx for a button's OnSelect
If(
    IsBlank(Trim(txtPrompt.Text)) || Len(Trim(txtPrompt.Text)) < 3,
    Notify("Please enter at least 3 characters.", NotificationType.Error),
    Set(
        aiResult,
        YourConnector.chat(
            {
                prompt: Trim(txtPrompt.Text)
            }
        ).response
    )
);

// Display result in a Label: Text = aiResult

Tip: Add input length limits and debouncing for multi-keystroke actions. For read-only UI against data, prefer server-side pagination and AsNoTracking() on the API layer where EF Core is involved.

Best Practices & Security

Identity and RBAC

  • Use Managed Identity for the Function App; never store secrets. The sample uses DefaultAzureCredential.
  • Assign the Cognitive Services OpenAI User role to the Function’s identity on the Azure OpenAI resource. This allows API calls without exposing keys.
  • Enforce Azure AD with Easy Auth at the platform level and verify identity in code for defense in depth.

Least Privilege and Network

  • Restrict access with the minimum RBAC scope necessary. Avoid granting Contributor on the subscription.
  • Enable HTTPS only and TLS 1.2+. Disable FTP/FTPS where possible.
  • Consider Private Endpoints for Azure OpenAI and Functions behind an Application Gateway/WAF for enterprise networks.

Validation, Error Handling, and Reliability

  • Validate input on both client (Power Apps) and server (Function). The code enforces content-type and schema shape.
  • Handle exceptions using middleware and return generic messages with correlation IDs to avoid leaking internals.
  • Implement circuit breakers and retries for downstream calls with transient fault policies if you add HTTP dependencies.

Observability

  • Use Application Insights. Log prompt sizes and latency, not raw sensitive content.
  • Sample KQL to investigate errors:
// Requests by operation
requests
| where url endswith "/chat"
| summarize count() by resultCode

// Exceptions with correlation
exceptions
| where operation_Name == "chat"
| project timestamp, type, problemId, outerMessage, operation_Id

// Latency p95
requests
| where url endswith "/chat"
| summarize p95(duration) by bin(timestamp, 1h)

Cost and Abuse Controls

  • Apply rate limiting at the API Management layer if exposing broadly.
  • Set MaxTokens and Temperature conservatively; monitor usage with budgets and alerts.
  • Implement content filters as needed using Azure AI Content Safety.

Summary

  • Power Apps integrates cleanly with AI by calling a secure .NET 8 Azure Function that uses Managed Identity to access Azure OpenAI.
  • Security is enforced with Azure AD (Easy Auth) and RBAC, specifically the Cognitive Services OpenAI User role.
  • IaC with Bicep, defensive coding, and Application Insights deliver repeatable, production-grade operations.