简体   繁体   中英

Calling Azure function from VM using managed identity and REST API

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?

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM