如何使用Rest-api在sharepoint中获取访问令牌?

时间:2018-02-01 06:47:29

标签: jquery rest sharepoint microsoft-graph sharepoint-online

我正在尝试访问我在Microsoft graph explorer中使用以下查询的共享点Excel图表

https://graph.microsoft.com/v1.0/sites/yyyyyy.com/drives/folderiddd/items/id2222/workbook/worksheets('Sheet1')/charts('Chart 2')/Image(width=300,height=300,fittingMode='fit')

这是结果。

在inspect元素的网络选项卡中,我得到了Authorization,我创建了Jquery ajax来获取sharepoint中的内容

var fileCollectionEndpoint = "https://graph.microsoft.com/v1.0/sites/yyyyyy.com/drives/folderiddd/items/id2222/workbook/worksheets('Sheet1')/charts('Chart 2')/Image(width=300,height=300,fittingMode='fit')";


$.ajax({
  url: fileCollectionEndpoint,
  async: false,
  dataType: 'json',
  type: "GET",
  headers: {
    'Authorization':'This is copied from the Microsoft graph explorer',
  },
  success: function (json) {
    var imgsource ="data:image/png;base64,"+json.value;
    $("body").append("<img id='ddd' src='"+imgsource+"' />");
  }
});     

上面的代码工作正常。但问题是这个令牌过期后每隔一小时我就会尝试使用rest-api生成令牌,因为每次我都无法从Microsoft Graph Explorer中复制粘贴。我该怎么做?

2 个答案:

答案 0 :(得分:2)

Graph explorer非常适合测试API调用,但就像您发现访问令牌在一小时后过期一样,因此您需要使用我们的令牌端点为您的应用获取令牌。在Get access tokens to call Microsoft Graph,这是一个很好的指南。总之,请在apps.dev.microsoft.com注册您的应用,然后决定您的应用是let users authenticate还是app will run in a server/daemon context without user authentication

我不确定您的问题,但如果您在SharePoint中进行开发还有其他选择,那么用户就不必在SharePoint内部登录您的应用。

using GraphHttpClient to call Microsoft Graph 的SharePoint文档页面。它使用Yeoman SharePoint生成器,其中包含Scaffold projects by using Yeoman SharePoint generator的设置指南。

步骤:

安装npm package

npm install @microsoft/generator-sharepoint -g

通过运行Yeoman SharePoint生成器创建新的Web部件。

mkdir hellograph-webpart
cd hellograph-webpart
yo @microsoft/sharepoint

在设置完成后,您可以导入GraphHttpClient以对Microsoft Graph进行REST调用。

import { GraphHttpClient, HttpClientResponse, IGraphHttpClientOptions } from '@microsoft/sp-http';
protected _readGroups(){

   this.context.graphHttpClient.get(`v1.0/sites/yyyyyy.com/drives/folderiddd/items/id2222/workbook/worksheets('Sheet1')/charts('Chart2')/Image(width=300,height=300,fittingMode='fit')`, GraphHttpClient.configurations.v1).then((response: HttpClientResponse) => {
     if (response.ok) {
       return response.json();
     } else {
       console.warn(response.statusText);
     }
   }).then((result: any) => {
     // Transfer result values to the group variable
     this._renderTable(result.value);
   });
}

答案 1 :(得分:0)

您需要从Microsoft图形中请求您尝试访问的SharePoint资源的访问令牌。

Get Auth Token

您可以使用ADAL Js使用OAuth为Sharepoint资源生成访问令牌。

ADAL JS