Search code examples
c#azure-functionsaccess-tokencsomazure-function-app

Token access blocked when posting request from published Azure function


I am struggling to get a token from "https://login.microsoftonline.com/common/oauth2/token" with an Azure function by a post-request. The token will give permissions to access SharePoint though CSOM. Here is my code snippet with the post request:

var clientId = defaultAADAppId;
var body = $"resource={resource}&client_id={clientId}&grant_type=password&username={HttpUtility.UrlEncode(username)}&password={HttpUtility.UrlEncode(password)}";
using (var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"))
{
    var result = await httpClient.PostAsync(tokenEndpoint, stringContent);
    var tokenResult = JsonSerializer.Deserialize<JsonElement>(result);
    var token = tokenResult.GetProperty("access_token").GetString();
}

When testing locally, both when running the function in Visual studio and when I try with Postman, I am able to achieve an access token. However, as soon as I publish the function to my Function app in Azure I receive the following error message:

"AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance"

I have enabled an app registration in the portal and as mentioned, it all works fine until I publish everything to Azure.

Any ideas on how to solve this?


Solution

  • I got it to work now. First of all I reviewed the CA policies as @CaseyCrookston suggested. What I found out was that our CA policies blocked calls outside the country we operate from. However, the calls from the App registration/Azure function were registered from the Azure data centre location and thus, blocked by our CA policies. When running them locally the calls where registered in my country and therefore no errors were showing while debugging.

    My first step was trying to add my Client app to the CA policy, which was not possible. The client/secret authentication that I used based on the suggestions in this CSOM guide by Microsoft prevented the App registration to be whitelisted from the CA policies (Github issue).

    Based on this I had to change the authentication to a Certificate-based authentication as suggested here: Access token request with a certificate and here: SO answer. With this I was able to whitelist the App registration in the CA policies and successfully authenticate to the Sharepoint CSOM.