EWS 错误消息:“403:禁止 - 范围不足”

EWS error message: "403: Forbidden - Not enough scopes"

上周我在这里提出了一个关于 EWS 的问题,在那里我收到了错误消息:

401: Unauthorized - Invalid access token

我设法通过使用 X.509 证书而不是客户端凭据(来自 AAD 的客户端 ID 和客户端密码)解决了这个错误。现在,使用证书后,我收到一条新的错误消息:

403: Forbidden - not enough scopes

我认为这与 AAD 中的权限有关?

我的权限如下(只有一个权限):

Application Permissions: Read and write email from all mailboxes

我如何接收访问令牌:

//Create the certificate file, using the path (certFile), password (certPassword) and the MachineKeySet
X509Certificate2 cert = new X509Certificate2(certFile, certPassword, X509KeyStorageFlags.MachineKeySet);

//Create the ClientAssertionCertificate using the clientID and the actual certificate
ClientAssertionCertificate cac = new ClientAssertionCertificate(clientID, cert);

//Retreive the access token using the serverName and client assertion
authenticationResult = authenticationContext.AcquireToken(serverName, cac);

//authenticationResult = authenticationContext.AcquireToken(serverName, cc);

ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013);
exchange.Url = new Uri(serverName + "ews/exchange.asmx");
exchange.TraceEnabled = true;
exchange.TraceFlags = TraceFlags.All;
exchange.Credentials = new OAuthCredentials(authenticationResult.AccessToken);

像这样调用FindItems方法时:

ItemView view = new ItemView(5);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);

var tempId = id.Replace('-', '/').Replace('_', '+');
SearchFilter.IsEqualTo searchid = new SearchFilter.IsEqualTo(ItemSchema.Id, tempId);

// This results in a FindItem call to EWS.
FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> results = exchange.FindItems(WellKnownFolderName.Inbox, searchid, view);

出现错误。

有人可以解释是什么导致了这种错误吗?

只有 Office 365 REST API 支持粒度访问,例如 "Read and write email from all mailboxes"。对于 EWS,您需要权限 "Use Exchange Web Services with full access to all mailboxes"。如果您在查找此权限时遇到问题,请告诉我们。

OAuth 流程不采用 X509Certificate2 身份验证。您应该在 AAD(Exchange Online 可用)中注册多租户应用程序。当您通过 OAuth 进行身份验证时,访问邮箱需要以下 3 个代理权限:

  • 阅读邮件
  • 阅读日历
  • 通过 Exchange Web 服务以登录用户身份访问邮箱

要向您的应用程序用户授予访问权限,应将其重定向到 https://login.microsoftonline.com/common/oauth2/authorize(使用相应的参数)。授予权限后,您会收到带有授权代码的响应,该授权代码应交换为 access/refresh 令牌:


    ClientCredential credential = new ClientCredential(clientId, appKey);
    AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common", false);
    var url = new Uri(Request.Url.GetLeftPart(UriPartial.Path));
    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                code, url, credential, "https://outlook.office365.com/");
 

其中 clientIdappKey - 已注册应用程序的参数,code - 是授权从 OAuth 响应中收到的代码。