SharePoint Rest API如何获取访问令牌?

31

我刚开始使用SharePoint和Microsoft认证,试图将SharePoint列表插入JavaScript应用程序中。根据Microsoft文档,我需要使用以下内容:

GET https://{site_url}/_api/web/lists/GetByTitle('List Title')
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"

我已经到处搜索了,想找到如何获取这个accessToken的明确答案。我能找到的所有来自Microsoft的文档似乎都过时了。有人知道获取accessToken的当前方法吗?


1
你可以看一下以下链接,这对我很有帮助:https://anexinet.com/blog/getting-an-access-token-for-sharepoint-online/ - Darrel K.
5个回答

31

为了调用SharePoint特定的API,您需要获取一个SPO特定的访问令牌。您可以通过执行以下操作将常规MS Graph刷新令牌“交换”为SPO特定令牌:

  1. 像平常一样从Graph中获取委托的身份验证令牌 (https://learn.microsoft.com/en-us/graph/auth-v2-user)
  2. 使用您获得的refresh_token,并再次调用auth终结点将其交换为SPO访问令牌:
POST https://login.microsoftonline.com/{{tenantName}}/oauth2/v2.0/token

使用以下表单数据:

client_id=<APP ID>
client_secret=<APP SECRET>
refresh_token=<REFRESH TOKEN FROM ABOVE>
grant_type=refresh_token
scope=https://<YOUR TENANT NAME>.sharepoint.com/Sites.Read.All
  1. 获取访问令牌并调用SPO API

您必须确保您的应用程序已注册正确的权限。例如,在上面的情况下,应用程序必须具有Sites.Read.All权限。


2
应该将其标记为答案!谢谢,它真的有效。 @chris-johnson,如果能在文档中分享关于这种方法的链接参考资料就太好了。 - 23W
2
@chris-johnson 你真是太棒了。我花了一整天的时间寻找解决方案,只有你的答案帮助了我。现在完美运作! - xalien
@Chris Johnson,我正在使用 MSAL,但在 IAuthenticationResult 对象中没有收到刷新令牌的响应,只有 accessToken。但是,我使用此 accessToken 无法访问 Sharepoint。请帮忙看看。版本:msal 2.2.3 - Rakesh
@Chris Johnson,他们不再公开刷新令牌。在这种情况下,我们如何访问SPO? - Rakesh
1
对于像我一样卡在这里的其他人,只是想提醒一下(我一直试图使用图形令牌与SPO一起使用,认为上面的1、2点是不同的可能性)。它们是应该按顺序遵循的步骤,哈哈。 - Herz3h

9

有没有更改访问令牌生命周期的选项? - dk7
我已成功获取访问令牌,但在请求_api/web时遇到问题。响应 - 状态:403 Forbidden。尝试执行未经授权的操作。请您给予建议吗? - Bohdan
@Bohdan - 你解决了403问题吗?我在使用访问令牌后遇到了同样的问题。 - VitalyT
@VitalyT _api/web - 这对我来说是错误的URL,这就是403错误的原因。但是同样的令牌在另一个URL上成功工作:https://{您的SharePoint站点URL}/sites/{您的站点名称}/_api/web - Bohdan

1

SP API的文档并不多,但它仍然有效。您可以按照文档使用适合您情况的身份验证类型获取Graph API的令牌,但是不要传递Graph API的范围(即“https://graph.microsoft.com/.default”),而应该传递SharePoint API的范围,即“https://{您的租户名称}.sharepoint.com/.default”

“.default”将为您提供具有在Azure AD中分配的所有权限的访问权-因此还确保Azure管理员已授予您所需的SharePoint API的API权限。

这也适用于MSAL。


0
export const pca = new PublicClientApplication(msalConfig);
// Create an Axios instance

export const sharepointApiCall = axios.create({ baseURL: `${BASE_URL}/_api` });

// MSAL.js v2 exposes several account APIs, logic to determine which account to use is the responsibility of the developer

const account = pca.getAllAccounts()[0];

// Define your access token request configuration

const accessTokenRequest = {
  //note: leave this scopes for possible future extension - ms has no docs for the names
  // scopes: [
  //   'openid',
  //   'profile',
  //   'email',
  //   'allsites.fullcontrol',
  //   'allsites.manage',
  //   'allsites.read',
  //   'allsites.write',
  //   'sites.fullcontrol.all',
  //   'sites.manage.all',
  //   'sites.read.all',
  //   'sites.readwrite.all',
  //   'user.read',
  //   'user.read.all',
  // ],
  scopes: [`${tenantName}/.default`],



 // other token request options
  account,
  redirectUri: 'http://localhost:3001',
};

// Add an Axios interceptor

sharepointApiCall.interceptors.request.use(async (config) => {
  try {
    const accessTokenResponse = await pca.acquireTokenSilent(accessTokenRequest);
    const accessToken = accessTokenResponse.accessToken;

// Add the token to the request headers
config.headers['Authorization'] = `Bearer ${accessToken}`;
    return config;
  } catch (error) {
    console.error('Error acquiring token:', error);
    return Promise.reject(error);
  }

});

那个范围:[租户]是@kadis解决方案,它可以工作,
令牌会自动刷新和缓存,所以不需要复杂的拦截 - 但是通过这种方式,您可以更轻松地使用React Query调用SharePoint的REST API,如果出现错误,则可以使用useMsal进行登录/注销。
希望对将来的任何人有所帮助。

0
如果您只需要使用用户名/密码登录并调用REST API,例如下载文件,以下是您需要执行的步骤。
您可以直接请求访问您的SharePoint,无需使用刷新令牌获取新的访问令牌,正如第一个答案中所描述的 - 感谢上帝,感谢那个答案。
curl --location --request GET 'https://login.microsoftonline.com/[TENANT ID]/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=[AAD APPLICATION CLIENT ID]' \
--data-urlencode 'scope=https://[YOUR DOMAIN].sharepoint.com/Sites.Read.All' \
--data-urlencode 'username=[USER THAT HAS ACCESS TO THE SITE]' \
--data-urlencode 'password=[PASSWORD OF THAT USER]' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_secret=[AAD APPLICATION CLIENT SECRET]'


curl --location 'https://[YOUR DOMAIN].sharepoint.com/sites/_api/web/lists/GetByTitle('\''Documents'\'')/files' \
--header 'Authorization: Bearer [ACCESS TOKEN FROM PREVIOUS STEP]'

记得给AAD应用程序添加Graph API权限Sites.Read.All。还有SharePoint权限AllSites.Read,不确定它们是否是同一件事,但我使用第一个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接