Skip to main content

Access Azure Function App via OAuth 2.0 authentication

This is a guide to protect Azure Function executions using OAuth 2.0. So the execution of the code is not possible without Client ID and ClientSecret. This allows a much more secure authentication than just using function codes in the URL in the query.

Disable authentication

To use the function with OAuth 2.0, the authentication on the function itself must first be set to Anonymous.

image.png

 

Identity provider

Then a new identity provider must be added to the Azure Function App. This can be done by going into the blade "Authentication":

image.png

There you have to select "Microsoft" as the identity provider. There you can decide if you want to use an existing App Registration or want to create one.

image.png

It is also recommended to send a 401 Unauthorized Response for incorrectly authenticated requests.

Afterwards, the app registration has to be adjusted so that the token handling works properly. To adjust the URL, the identity provider must be adjusted using "Edit".

image.png

The issuer URL must be adjusted. The "/v.2.0" at the end must be removed 

image.png

Authentication via PowerShell

Then PowerShell can be used to authenticate against the app registration. The App Registration then has permissions to execute all Azure Functions in the Azure Function App.

$TenantId ="<yourtenantid>"
$ClientID = "<yourclientid>"
$ClientSecret = "<yourclientsecret>"

$FunctionAppId = "<yourfunctionappid>" 
$FunctionApiAuthUrl = "$functionuri/.auth/login/aad" 
$functionapi = "/api/HttpTrigger2"

# Authenticate against MEID to get access token with App Registration Client Secret
$Body = @{ 
    "tenant" = "$TenantId" 
    "client_id" = "$ClientID" 
    "scope" = "api://$functionappid/.default" 
    "grant_type" = "client_credentials" 
    "client_secret" = $ClientSecret 
} 

$Params = @{
    "Uri" = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
    "Method" = "Post"
    "Body" = $Body
    "ContentType" = "application/x-www-form-urlencoded"
}
    
$AuthResponse = Invoke-RestMethod @Params

Function execution via PowerShell

The second part of the authentication is to ask the function api for a token and then execute it using the token received:

# Authenticate against function with the MEID access token
$FunctionAuthBody = @{ 
    "access_token" = $AuthResponse.access_token 
}

$functionToken = Invoke-RestMethod -Method POST -Uri $FunctionApiAuthUrl -Body (ConvertTo-Json $FunctionAuthBody) -ContentType "application/json" 

$Header = @{ 
    "X-ZUMO-AUTH" = $functionToken.authenticationToken 
}

# Run Azure Function with OAuth2.0 Token Authentication
Invoke-RestMethod -Method POST -Uri $functionuri$functionapi -Headers $Header