要在不使用用户名和密码的情况下对SharePoint Online REST API进行身份验证,可以使用OAuth 2.0授权框架。以下是实现这一目标的步骤:
Sites.FullControl.All
)。使用客户端ID和客户端密钥获取访问令牌。可以通过以下几种方式实现:
https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token
{tenant-id}
替换为你的Azure AD租户ID。x-www-form-urlencoded
。grant_type
: client_credentials
client_id
: 你的应用程序客户端IDclient_secret
: 你生成的客户端密钥scope
: https://graph.microsoft.com/.default
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
public class TokenProvider
{
private const string TenantId = "{tenant-id}";
private const string ClientId = "{client-id}";
private const string ClientSecret = "{client-secret}";
public static async Task<string> GetAccessTokenAsync()
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{TenantId}"))
.Build();
var result = await app.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
return result.AccessToken;
}
}
获取访问令牌后,可以在HTTP请求头中包含该令牌来调用SharePoint REST API。
Authorization
头,并设置为 Bearer {access-token}
。using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class SharePointClient
{
private const string SharePointSiteUrl = "{sharepoint-site-url}";
public static async Task<string> GetListItemsAsync(string accessToken)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync($"{SharePointSiteUrl}/_api/web/lists/getbytitle('Documents')/items");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
通过上述步骤,你可以使用OAuth 2.0授权框架在不使用用户名和密码的情况下对SharePoint Online REST API进行身份验证。这种方法不仅提高了安全性,还简化了身份验证过程。
领取专属 10元无门槛券
手把手带您无忧上云