首页 > 解决方案 > 通过 Microsoft.Graph 邀请用户会出错

问题描述

预期行为

应该邀请用户然后使用更多信息更新用户 https://docs.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 Code - 1.31.1 Vsiual Studio Enterprise 2017 - 4.7.03056

我有这个方法(将创建 GraphServiceClient 的代码移动到证明点的方法中)客户端通过 App 注册进行身份验证(我得到一个访问令牌)但是当 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; }
    }

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

权限: 权限

IConfiguration 对象中的应用程序 ID 配置

标签: c#azuremicrosoft-graph-apiasp.net-core-2.2

解决方案


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

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

此外,由于您具有异步功能,因此最好也等待令牌:

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

推荐阅读