无法通过 MS Graph 中的 ROPC 访问站点和 onedrive API

Not having access to sites and onedrive via ROPC in MS Graph API

我使用以下代码获取 MS Graph API 访问令牌:

# Resource Owner Password Credentials (ROPC)
def ropc_flow_session(AUTHORITY, RESOURCE, username, password, CLIENT_ID):
  context = adal.AuthenticationContext(AUTHORITY)
  token_response = context.acquire_token_with_username_password(RESOURCE, username, password, CLIENT_ID)

  session = requests.Session()
  session.headers.update({'Authorization': f'Bearer {token_response["accessToken"]}'})
  
  return session

RESOURCEAUTHORITY 的值为:

RESOURCE = 'https://graph.microsoft.com'
AUTHORITY = F"https://login.microsoftonline.com/{tenant}"

当我调用 ropc_flow_session 函数时,它 returns session 包含以下 header:

{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Bearer {ACCESS_TOKEN_VALUE}'}

所以我的理解是我可以访问已注册的应用程序。
当我尝试用 https://graph.microsoft.com/v1.0/me 调用 me 时,错误消息 says:l

 {'error': {'code': 'Authorization_RequestDenied',
            'message': 'Insufficient privileges to complete the operation.',

我试图通过 https://graph.microsoft.com/v1.0/sites/{TENANT}:/sites/{SITE_NAME}:/drives 访问用户是所有者的共享库,但它引发了:

 {'error': {'code': 'accessDenied',
            'message': 'Access denied. You do not have permission to perform this action or access this resource.',

这是已注册应用的列表API权限:

根据错误消息,我似乎已作为应用程序连接,但我使用了 ROPC 并传递了特定用户的用户名和密码。 任何想法表示赞赏

[更新] 这是我从 jwt.ms 获得的解码令牌:

我已经在评论中提到了,但是为了让其他有同样问题的人清楚,我在这里做了更多的描述。 就我而言,问题是注册的 Azure 应用程序有两个所有者。一个是我自己的工作帐户,另一个是服务帐户。我用我的工作帐户添加了委派权限,它显示在 API 权限列表中。但是当我检查 Enterprise applications link 时,它显示所有用户同意权限仅限于 1 个特定用户

您可以通过单击 Enterprise applications 并查看 user consent 选项卡来检查


有两种解决方法:

  1. 请管理员也为其他用户授予管理员许可(在我的例子中,它是一个服务帐户)
  2. 使用其他用户(在我的例子中是服务帐户)登录并添加相同的 API 权限
    我希望这可以帮助其他人解决同样的问题

感谢@shiva-keshav-varma对评论的有益建议