Can we make REST API calls to an azure function from an Azure VM? We cannot store user name and password for the API. Is there any other authentication we can use to make a call to the azure function? eg: Managed identity, certificates?
1 Answers
Yes, you could use Managed identity(MSI) to get the token, then use the token to make REST API call to your azure function, please follow the steps below.
1.Navigate to the VM in the portal -> Identity
-> enable the System-assigned identity.
2.Navigate to the function app in the portal -> Authentication / Authorization
-> configure your function app with Azure AD auth, follow this doc, don't forget to set the Log in with Azure Active Directory
, after configuration, it will take a while to create an AD App for your function app, it will appear like below at last.
3.Then in the function app, create an HTTP trigger to have a test, Note: its Authorization level
needs to be set as Anonymous
.
4.In my sample, I RDP into the VM, then use the powershell to get the token, then use the token to call the function, in your case, you can also use other languages depends on your requirements. My function name is joyfun111
, replace it with yours in the script, it works on my side.
$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://joyfun111.azurewebsites.net' -Method GET -Headers @{Metadata="true"}
$content = $response.Content | ConvertFrom-Json
$Token = $content.access_token
Invoke-RestMethod -Uri 'https://joyfun111.azurewebsites.net/api/HttpTrigger1?name=world' -Method POST -Headers @{Authorization="Bearer $Token"}
Update:
If so, you just need to use the function key along with the function url, change the Authorization level
to Function
, disable the Azure AD auth in Authentication / Authorization
, then use the command like below.
Invoke-RestMethod -Uri 'https://joyfun111.azurewebsites.net/api/HttpTrigger1?code=10X/IKJIeElrCRIxxxxH6A==&name=world' -Method POST -UseBasicParsing
You can get the function url in the function page.