图 API - 更新现有用户 - 权限不足,无法完成操作

Graph API - Update existing User - Insufficient privileges to complete the operation

我目前正在开发一个与 Graph 通信的应用程序 API。我没有任何后端,只有 SPA。我使用 npm 包 @microsoft/microsoft-graph-client.

该应用程序应该能够更改 ad 用户的 givenName、姓氏。

一开始我创建了一个新的 AuthCodeMSALBrowserAuthenticationProvider 实例并将其与图形客户端一起使用,我不确定使用的范围是否正确:

 const authProvider = new AuthCodeMSALBrowserAuthenticationProvider(
        this.msalService.instance as PublicClientApplication,
        {
          account: this.msalService.instance.getActiveAccount()!,
          scopes: ['User.ReadWrite.All'],
          interactionType: InteractionType.Redirect,
        }
      );

 this.graphClient = Client.initWithMiddleware({
        authProvider: authProvider,
        defaultVersion: 'beta',
      });

我的电话是这样的

 const result = await this.authService.graphClient
        .api(`/users/${userId}`)
        .patch({
          givenName: firstname,
          surname: lastname
        });

但是,我收到“权限不足”错误消息。

Could not update user with id 8639e42f-de7f-485a-9b18-ccd67d7b0146 {
  "statusCode": 403,
  "code": "Authorization_RequestDenied",
  "requestId": "xy",
  "date": "2022-02-03T11:45:48.000Z",
  "body": "{\"code\":\"Authorization_RequestDenied\",\"message\":\"Insufficient privileges to complete the operation.\",\"innerError\":{\"date\":\"2022-02-03T12:45:48\",\"request-id\":\"xy\",\"client-request-id\":\"xy\"}}"
}

我设置了以下权限(在“企业应用程序”下):

API 权限(在“应用程序注册”下):

请确保您已授予授权管理员许可。

我使用 implicit flow 进行了相同的测试,我在其中创建了一个 Azure AD 应用程序并提供了如下所示的 Delegated Permission,但未授予管理员同意:

在获得管理员许可后,问题已解决,如下所示:

您可以在此处查看权限参考,以设置正确的范围:https://docs.microsoft.com/en-us/graph/permissions-reference#mail-permissions

你要注意"In delegated scenarios, the effective permissions granted to your app are constrained by the privileges of the signed-in user in the organization."

如果您的应用是守护进程(无需人工交互的后端服务)you should use "Application permission" instead of "Delegated permission"

您可以根据此处的情况选择正确的身份验证提供程序和正确的权限类型:https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=Javascript

PS : 您应该隐藏第二个屏幕截图的状态栏,因为它显示了私人信息。