Microsoft Graph API 是微软提供的统一 RESTful API 接口,用于访问 Microsoft 365(如 Outlook、OneDrive、Teams 等)中的数据和服务。在 Xamarin 应用程序中集成 Microsoft Graph API 时,作用域(Scopes) 是 OAuth 2.0 授权机制中的关键概念,用于定义应用程序请求访问用户数据或执行操作的权限范围。
Microsoft Graph API 的作用域分为两类:
User.Read
:读取用户基本信息。Mail.Read
:读取用户邮件。Calendars.ReadWrite
:读写用户日历。Mail.Read
(应用权限):读取所有用户的邮件。User.Read.All
:读取所有用户信息。User.Read
实现微软账号登录。Mail.ReadWrite
或 Calendars.Read
同步邮件或事件。Files.ReadWrite
访问 OneDrive 文件。以下是在 Xamarin 中配置 Microsoft Graph API 作用域的典型步骤:
using Microsoft.Identity.Client;
var scopes = new[] { "User.Read", "Mail.Read" }; // 定义所需作用域
var clientApplication = PublicClientApplicationBuilder
.Create("你的客户端ID")
.WithRedirectUri("msal{客户端ID}://auth") // Android 需配置 Intent Filter
.Build();
// 获取令牌
var authResult = await clientApplication.AcquireTokenInteractive(scopes)
.WithParentActivityOrWindow(/* 传入 Activity */)
.ExecuteAsync();
// 使用令牌调用 Graph API
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(requestMessage =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
return Task.CompletedTask;
}));
var messages = await graphClient.Me.Messages
.Request()
.Select(m => new { m.Subject, m.ReceivedDateTime })
.GetAsync();
msal{ClientId}://auth
msal{ClientId}://auth
+ 在 Info.plist
中注册 URL Scheme。Mail.Read
)。通过合理配置作用域,Xamarin 应用可以安全高效地集成 Microsoft 365 生态的能力。
没有搜到相关的文章