Connect from PowerShell to Function app with Azure AD Join device identity

172 Views Asked by At

i have an internal reporting application and i run it in system context?

I want to use the local azure ad identity to connect and authenticate to the app which is configured to Azure AD integration.

It looks like there is a certificate enrolled on the device from Azure AD Domain join - but how do I use the certificate to get a Token for the Function App?

1

There are 1 best solutions below

0
On

In order to enable Function App Authentication with Azure AD Joined App or Azure AD app. Refer the steps below:-

enter image description here

Add your Azure AD Certificate in the Key vault and give the Azure AD App access to the certificate via Access Policy or RBAC refer here.

Then run the below code in the Powershell Function HTTP Trigger:-

using namespace System.Security.Cryptography.X509Certificates

# Define your AppId, TokenURI, and Resource
$AppId = "xxxxb838-6d26a31435cb"
$TokenURI = "https://login.microsoftonline.com/7xxxxf3b-4425-a6b6-09b47643ec58/oauth2/token"
$Resource = "https://management.core.windows.net/"

# Define the URL of the certificate stored in Azure Key Vault
$CertificateUrl = "https://your-keyvault.vault.azure.net/secrets/your-certificate-secret"

# Prepare the body request
$BodyRequest = @{
    grant_type = "client_credentials"
    client_id = $AppId
    client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
    client_assertion = [System.Convert]::ToBase64String((Get-AzKeyVaultCertificateOperation -VaultName "your-keyvault" -CertificateName "your-certificate-name").Result)
    resource = $Resource
}

$AccessToken = Invoke-RestMethod -Method Post -Uri $TokenURI -Body $BodyRequest

# Now you can make the request to list all resources
$SubscriptionId = "6912d7a0-bc28-459a-9407-33bbba641c07"

$RequestURI = "https://management.azure.com/subscriptions/$SubscriptionId/resources?api-version=2021-04-01"

$Headers = @{
    Authorization = "Bearer " + $AccessToken.access_token
}

$ResourceRequest = Invoke-RestMethod -Method Get -Uri $RequestURI -Headers $Headers

# Return the results as a response
$Response = @{
    StatusCode = 200
    Body = $ResourceRequest.value | ConvertTo-Json
}

Refer this SO thread answer for the same scenario.