1

I have a azure function and making a CSOM call to SharePoint online. The authentication was done with App ClientId & ClientSecret. Everything working fine. I am capturing a DocSet version via CSOM call (its available only with CSOM) and CreatedBY is showing as "SharePoint App". I would like to make this azure call to run with currently signed in user.. i.e. CreatedBy should show current user's name. Kindly help.

    public static class CaptureDocSetVersion
  {
    [FunctionName("CaptureDocSetVersion")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequestMessage req, TraceWriter log)
    {
      log.Info("C# HTTP trigger function processed a request.");

      // parse query parameter
      var qs = req.RequestUri.ParseQueryString();

      string itemId = qs.Get("id");

      if (itemId == null)
      {
        // Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();
        itemId = data?.itemId;
      }
      if (string.IsNullOrWhiteSpace(itemId))
        return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a item id on the query string or in the request body");
      
      try
      {
        log.Info("Item id:" + itemId);
        string result = CaptureDocSetVersion.CaptureVersion(itemId);
        log.Info(result);
        return req.CreateResponse(HttpStatusCode.OK, "Version captured for item " + itemId);
      }
      catch (Exception ex)
      {
        log.Info("Error occured :" + ex.ToString());
        return req.CreateResponse(HttpStatusCode.InternalServerError, "Error ocurred while capturing the docset version");
      }
    }

    private static ClientContext GetonlineContext()
    {
      string ServiceSiteUrl = ConfigurationManager.AppSettings["ContractSiteUrl"];
      var clientID = ConfigurationManager.AppSettings["ClientId"];
      var clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
      //ideally this should be done with SSO once identity provider issue is fixed
      var authManager = new OfficeDevPnP.Core.AuthenticationManager();
      ClientContext clientContext = authManager.GetAppOnlyAuthenticatedContext(ServiceSiteUrl, clientID, clientSecret);
      return clientContext;      
    }

    public static string CaptureVersion(string itemId)
    {
      var listId = ConfigurationManager.AppSettings["ContractFormListId"];
      var ctx = GetonlineContext();
      ctx.Load(ctx.Web);
      var list = ctx.Web.Lists.GetById(new Guid(listId));
      var item = list.GetItemById(itemId);
      ctx.ExecuteQuery();
      var folder = item.Folder;
      ctx.Load(folder);
      var ds = Microsoft.SharePoint.Client.DocumentSet.DocumentSet.GetDocumentSet(ctx, folder);
      ctx.Load(ds);
      var dsVersions = ds.VersionCollection;
      dsVersions.Add(true, "Captured through azure function app");
      ctx.ExecuteQuery();
      return "CSOM code executed";
    }
  }

SPFx call here

public captureVersion = async (id: number): Promise<any> => {
        let azADClient: AadHttpClient = await this.context.aadHttpClientFactory
            .getClient('a7a4b1df-b30c-44fa-b0be-9dd2ab9647ab');
        let url = `${constants.CAPTUREDOCSETVERSION_AZFUNC_URL}&id=${id}`;
        const requestHeaders: Headers = new Headers();
        requestHeaders.append('Content-type', 'application/json');

        const httpClientOptions: IHttpClientOptions = {
            headers: requestHeaders
        };

        try {
            let response: HttpClientResponse = await (azADClient.get(
                url, AadHttpClient.configurations.v1, httpClientOptions));
            // let response: HttpClientResponse = await (this.context.httpClient.get(
            //     url, HttpClient.configurations.v1, httpClientOptions));
            let json = await response.json();
            return json;
        } catch (e) {
            console.log(e);
        }
    }

Here is the Azure Identity provider information

SharePoint Online Client Extensibility Web Application Principal

API Permissions

User.Read and user_impersonation

Whenever I am making SPFx call I am gettin HTTP status 500 and azure function was never hit.. Also, the Azure function app is going into "Azure functions runtime is unreachable state" and I am forced to delete and recreate the Azure Function App again.

2
  • 1
    What are you using to trigger the Azure function? A button inside an SPFx solution? or something else? Apr 16, 2021 at 17:34
  • Yes.. A button inside a SPFx form. It is to capture DocSet version and its available only with CSOM.. (Not in PnPJS or REST API).. [link] nivas.org/…
    – san
    Apr 18, 2021 at 0:57

1 Answer 1

0

If you following this article, then you'll be able to call SharePoint API from an Azure function using currently logged in user in an SFPx webpart/extension: Consume enterprise APIs secured with Azure AD in SharePoint Framework

This article illustrates how you would connect to an enterprise API secured with Azure Active Directory from a SharePoint Framework solution. It covers both creating and securing the API as well as building the SharePoint Framework solution.

1
  • I've made several unfruitful attempts.. I've added all the code the above.. am I missing anything? Appreciate if you could help.
    – san
    Apr 25, 2021 at 7:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.