首页 > 解决方案 > 自定义函数中的 asp.net API cookie 身份验证

问题描述

如何从使用自定义函数内部的 cookie 身份验证的 asp.net API 获取数据。

我遵循了https://docs.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-web-reqs中的示例。我可以发出请求,但 fetch 似乎没有在后续请求中包含 cookie。似乎 fetch 在自定义函数中被削弱了。

/**
 * @customfunction
 */
async function CalcbenchData(): Promise<number> {
  let batchURL = 'https://www.calcbench.com/api/NormalizedAPIBatch'
  let data = [{ "metric": "revenue", "ticker": "msft", "year": 2015, "period": 1, "datatype": 1 }]
  await login()
  return postData(batchURL, data)
}

/**
* the reponse from this function sets the ASP.net authentication token cookie
*/
async function login() {

  let email = encodeURIComponent('username')
  let password = encodeURIComponent('password')
  let url = `https://www.calcbench.com/account/LogOn?email=${email}&password=${password}`

  await fetch(url,{
    method: 'GET',
    mode: 'same-origin'
  });
}


function postData(url = '', data = {}): Promise<number> {
  return fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'same-origin', // no-cors, cors, *same-origin

    headers: {
      'Content-Type': 'application/json',
    },

    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // no-referrer, *client
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  }).then(response => {
    return response.json()
  }).then(json => {
    return json.value
  }) // parses JSON response into native JavaScript objects 
}

7/25/2019 17:49:54 详细运行时 [Console] [Log] Unexpected CustomFunctions [Execution] [End] [Failure] [RejectedPromise] Function=CALCBENCHDATA TypeError: Network request failed {}

标签: javascriptoffice-jscustom-functions-excel

解决方案


这目前在 Windows 上的自定义函数运行时是不可能的(因为它是与身份验证对话框分开的过程),但我们正在积极开发如何启用它。请在 GitHub 上观看此项目以了解即将发布的更新:https ://github.com/OfficeDev/Excel-Custom-Functions/issues/118 。我们可能会在几周内对其进行更新。

谢谢


推荐阅读