调用Microsoft Graph获取用户UsageRights时遇权限及回调地址错误
针对Excel Web Add-in调用Graph UsageRights API的问题解决方案
问题1:外部域用户调用API返回AccessDenied
解决方案:
验证权限范围与令牌有效性
调用usageRightsAPI需对应权限:- 委派权限:需包含
Directory.AccessAsUser.All(配合User.Read) - 应用权限:需包含
User.Read.All或Directory.Read.All
确认应用已在Microsoft Entra ID中添加上述权限,且授权流程请求了这些范围。通过jwt.ms解码accessToken,检查scp(委派权限)或roles(应用权限)字段是否包含所需权限,同时确保aud字段值为https://graph.microsoft.com。
- 委派权限:需包含
处理外部租户权限授权
内部域租户已授权应用访问,但外部域(如abc.com)租户管理员未同意应用权限请求。需引导外部租户管理员完成管理员同意流程,或在授权请求中添加prompt=admin_consent参数触发管理员同意。修正API请求路径
建议使用authResult.Account.Username代替HomeAccountId.ObjectId作为用户标识,避免跨租户场景下的ID不匹配:string url = $"https://graph.microsoft.com/beta/users/{authResult.Account.Username}/usageRights";
问题2:使用Graph Client时返回reply地址不匹配错误
解决方案:
显式指定重定向URI
创建AuthorizationCodeCredentialOptions时必须设置与授权码请求一致的RedirectUri:var options = new AuthorizationCodeCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud, RedirectUri = new Uri("https://localhost:53054/AzureADAuth/Authorize") };更新权限范围
scopes数组需包含访问usageRights的必要权限:var scopes = new[] { "User.Read", "Directory.AccessAsUser.All" };避免重复使用授权码
授权码仅能使用一次,若已在方法1中消费过该授权码,建议直接复用已获取的accessToken初始化Graph Client:var graphClient = new GraphServiceClient( new DelegateAuthenticationProvider(requestMessage => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return Task.CompletedTask; }), scopes); var result2 = await graphClient.Me.UsageRights.GetAsync();
内容的提问来源于stack exchange,提问作者Nitesh
相关产品推荐
相关产品推荐

