cloudradial / CloudRadialCsaAutomations

This repository contains Azure Function App functions that link the CloudRadial CSA service catalog directly to Microsoft 365, ConnectWise Manage, and other IT management tools.
MIT License
4 stars 17 forks source link

Request - Example of a connection to another tenants Azure context in Run Book/Azure Function #5

Open paulobriennz opened 7 months ago

paulobriennz commented 7 months ago

Hi, thank you for the Graph Connection example. Great you can now register a 'multi tenant' app in the primary tenant and set M365 Graph scopes.. I'm passing in the TenantId in the body of the Automation request to specify which customer tenant to work with.

Inside the Azure function, you are already connected to Azure (but in the root context the function is deployed in), but could you show an example of how to connect to a specific customers Azure context? is it similar to Graph where you create a multi tenant app and then use this app to 're-auth', passing in the specific TenantId or SubscriptionId? I've read up about managed identities etc, but most example don't show how to connect to another tenant's Azure context.

With the M365 Graph example, you implicitly make a connection to MgGraph, but as you are already Azure authenticated when running the function, can you advise the best way to connect to another tenant?

paulobriennz commented 4 months ago

Think I've figured Azure Connection out.

In the customers tenant, you need to get the ObjectId of the multi tenant app that you've registered. Then you need to create an Azure role assignment between this object and the subscription.

$AuthApp = Get-AzADServicePrincipal | Where-Object { $_.AppId -eq "xxx" } #the appId of your multi tenant app New-AzRoleAssignment -ObjectId $AuthApp.Id -Scope "/subscriptions/$($sub.id)" -RoleDefinitionName Owner

Then, inside your runbook, you can connect to the customers Azure context successfully.

$password = ConvertTo-SecureString $env:Secret -AsPlainText -Force $psCredentials = New-Object System.Management.Automation.PSCredential ($env:AppId, $password)

Disconnect-AzAccount Connect-AzAccount -ServicePrincipal -Credential $psCredentials -Tenant $tenantId