Search code examples
azureauthenticationsharepointazure-functionstoken

C# HTTP trigger function processed a request. Token request failed


I am getting this logged: [Error] C# HTTP trigger function processed a request. Token request failed. when I run the Azure Function from the portal.

When I test/run the app from Visual Studio (in my local) it successfully updates the item and I am unable to reproduce the issue.

Is there something wrong I am doing?

I am authenticating using app id/secret in PnP.Framework in an Azure Function like so:

        [FunctionName("RecordUpdate")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            Microsoft.Extensions.Logging.ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string responseMessage = string.Empty;

            string siteUrl = req.Query["siteUrl"];
            string listName = req.Query["listName"];
            string listItemId = req.Query["listItemId"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            siteUrl = siteUrl ?? data?.siteUrl;
            listName = listName ?? data?.listName;
            listItemId = listItemId ?? data?.listItemId;

            PnP.Framework.AuthenticationManager authenticationManager = new();
            try
            {
                string?[] appDetails = GetAppConfiguration(log);
                using (ClientContext context = authenticationManager.GetACSAppOnlyContext(siteUrl, appDetails[0], appDetails[1]))
                {
                    context.RequestTimeout = System.Threading.Timeout.Infinite;

                    List list = context.Web.Lists.GetByTitle(listName);
                    context.Load(list);
                    context.ExecuteQuery();

                    int id = 0;
                    bool isValidId = Int32.TryParse(listItemId, out id);

                    if (list != null)
                    {
                        if (isValidId)
                        {
                            ListItem item = list.GetItemById(id);
                            context.Load(item);
                            context.ExecuteQuery();

                            if (item != null) { /* my code to update Item goes here */ }
                        }
                    }
                }
            }
        }

Solution

  • See: Authentication for Azure Functions

    Based on the error message there is an issue with the authentication. Does GetAppConfiguration return the expected app id and secret? Make sure the app id used for authentication has the necessary permissions.

    If you've checked everything, then add some more detail logging to narrow down the issue: Return error details from Azure Function HttpTrigger