c# - 通过 Microsoft.Graph 邀请用户会出现错误

标签 c# azure microsoft-graph-api asp.net-core-2.2

预期行为

应邀请用户,然后用更多信息更新用户 https://learn.microsoft.com/en-us/graph/api/invitation-post?view=graph-rest-1.0

实际行为

来源

"Microsoft.Graph.Core"

留言

"Code: Unauthorized\r\nMessage: Insufficient privileges to perform requested operation by the application '00000003-0000-0000-c000-000000000000'. ControllerName=MSGraphInviteAPI, ActionName=CreateInvite, URL absolute path=/api/9cXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/invites\r\n\r\nInner error\r\n"

堆栈跟踪

   at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at Web.Api.Infrastructure.Infrastructure.Repositories.AzureRepository.CreateUser(CreateUserCommand user) in C:\Users\SamPrecious\source\repos\Adept\src\adept-web-api\Web.Api.Infrastructure\Infrastructure\Repositories\AzureRepository.cs:line 166

重现行为的步骤

SDK版本: netcoreapp2.2
“Microsoft.Graph”版本=“1.13.0” “Microsoft.Graph.Core”版本=“1.13.0”

IDE版本: VS 代码 - 1.31.1 Vsiual Studio 企业版 2017 - 4.7.03056

我有这个方法(将创建 GraphServiceClient 的代码移到该方法中以证明一点) 客户端通过应用程序注册进行身份验证(我得到一个访问 token ),但是当 Invite 的代码运行时,authenticationContext.AcquireTokenAsync 再次触发,并且我在上面的堆栈跟踪中收到错误。根据 API 文档,客户端应用程序具有 User.Invite.All、User.ReadWrite.All、Directory.ReadWrite.All。

为什么代码中的AppId会变成上面Message中的AppId?

public async Task<string> CreateUser(CreateUserCommand user)
        {
            try
            {
                var clientCredential = new ClientCredential(_configuration["appId"], _configuration["secret"]);
                var authenticationContext = new AuthenticationContext(_configuration["authority"]);
                var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential).Result;

                var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);

                    return Task.FromResult(0);
                });

                var con = new GraphServiceClient(delegateAuthProvider);

                //invite user
                Invitation invitation = new Invitation();
                invitation.InvitedUserDisplayName = user.Name;
                invitation.SendInvitationMessage = true;
                invitation.InvitedUserEmailAddress = user.Email;
                invitation.InviteRedirectUrl = "http://localhost";
                var result = await con.Invitations.Request().AddAsync(invitation);

                //update user
                var aadUser = _connection.GetConnection().ActiveDirectoryUsers.GetById(result.Id);
                var updateUser = result.InvitedUser;
                updateUser.DisplayName = user.Name;
                updateUser.Surname = user.Surname;
                updateUser.Mail = user.Email;
                updateUser.MobilePhone = user.Phone;
                await con.Users[result.InvitedUser.Id].Request().UpdateAsync(updateUser);
                return aadUser.UserPrincipalName;
            }
            catch (System.Exception)
            {

                throw;
            }


        }

创建用户命令:

public class CreateUserCommand
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

这是应用程序注册的捕获 appreg

权限: permissions

IConfiguration 对象中的应用程序 ID configuration

最佳答案

仅当您在用户上下文中调用 API 时,委派权限才有意义。

由于您使用的是客户端凭据,因此没有用户。 仅应用程序权限适用,因此请在那里设置正确的权限。

此外,由于您有一个异步函数,因此最好也等待 token :

var authenticationResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential);

关于c# - 通过 Microsoft.Graph 邀请用户会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55001009/

相关文章:

c# - View 中加载的某些资源未本地化,为什么?

azure - 创建 Azure SQL DB 服务器时, "This location is not available for subscriptions"

Python Django/with Microsoft Graphs - 我不断收到值错误 "state missing from auth_code_flow"

azure - v2.0 应用程序缺少 AppCatalog 资源权限

c# - 对运行时命中应用程序的 API 调用进行单元测试的最佳方法

c# - 即使进程正在运行,Process.HasExited 也会返回 true?

azure - 设置 kubernetes 集群时,kubeadm 初始化命令出现错误

azure - Azure CDN 和同一数据中心内的托管应用程序之间是否收费?

azure-active-directory - 使用应用程序 token 通过 REST API 调用 Microsoft Graph

C# 顶点边