代码之家  ›  专栏  ›  技术社区  ›  dmmfll

msal ConfidentialClientApplication成功获得承载令牌;Authorization_Request被拒绝,尽管授予了全部权限

  •  0
  • dmmfll  · 技术社区  · 4 年前

    提前感谢您的帮助。

    我正在尝试访问使用Microsoft Graph的组织的特定电子邮件帐户的电子邮件。

    我正在创建的Python应用程序需要阅读和转发位于“someuser@myorganization.com“.(我以前使用Python库exchangelib成功阅读了这些电子邮件,但现在Microsoft不再支持Basic Auth; exchangelib does not support Microsoft Graph )。

    该组织已在Microsoft身份平台上注册了一个应用程序“电子邮件服务应用程序”。似乎已授予完全权限。请参阅下面该组织发给我的屏幕截图。(我无权访问图形面板。)

    Screenshot of Service Email App API Permissions

    我一直在遵循GitHub存储库中为msal库提供的优秀示例: https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/sample/confidential_client_secret_sample.py

    我编写的代码确实成功地获得了一个承载令牌。

    我的期望是,有了这个持有者代币,我可以阅读特定电子邮件帐户的电子邮件:someuser@myorganization.com

    代码中的错误很简单:“权限不足,无法完成操作。”

    尽管如此,我还是感到困惑,因为似乎已经授予了完全权限。(请参阅上面的屏幕截图。)

    以下是我正在使用的代码:

    config_data = {
        "authority": "https://login.microsoftonline.com/<secret value>",
        "client_id": "<secret value>",
        "scope": ["https://graph.microsoft.com/.default"],
        "secret": "<secret value>",
        "endpoint": "https://graph.microsoft.com/v1.0/users"
    }
    # Optional logging
    logging.basicConfig(level=logging.DEBUG)  # Enable DEBUG log for entire script
    logging.getLogger("msal").setLevel(logging.INFO)  # Optionally disable MSAL DEBUG logs
    
    config = json.loads(config_data)
    
    # Create a preferably long-lived app instance which maintains a token cache.
    app = msal.ConfidentialClientApplication(
        config["client_id"], authority=config["authority"],
        client_credential=config["secret"],
    )
    

    日志输出:

    DEBUG:urllib3.util.retry:Converted retries value: 1 -> Retry(total=1, connect=None, read=None, redirect=None, status=None)
    DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): login.microsoftonline.com:443
    DEBUG:urllib3.connectionpool:https://login.microsoftonline.com:443 "GET /<secret>/v2.0/.well-known/openid-configuration HTTP/1.1" 200 1753
    

    代码继续:

    # The pattern to acquire a token looks like this.
    result = None
    
    # Firstly, looks up a token from cache
    # Since we are looking for token for the current app, NOT for an end user,
    # notice we give account parameter as None.
    result = app.acquire_token_silent(config["scope"], account=None)
    

    日志输出:

    INFO:root:No suitable token exists in cache. Let's get a new one from AAD.
    DEBUG:urllib3.connectionpool:https://login.microsoftonline.com:443 "POST /<secret>/oauth2/v2.0/token HTTP/1.1" 200 1589
    

    代码继续:

    if not result:
        logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
        result = app.acquire_token_for_client(scopes=config["scope"])
    

    日志输出:

    信息:根:缓存中不存在合适的令牌。让我们从AAD买一个新的。
    调试:urlib3.connectionpool:https://login.microsoftonline.com:443“POST/<secret>/oauth2/v2.0/token HTTP/1.1”200 1589
    

    代码继续:

    print(result)
    

    输出:

    {'token_type': 'Bearer',
     'expires_in': 3599,
     'ext_expires_in': 3599,
     'access_token': <removed, was successful>}
    

    代码继续:

    if "access_token" in result:
        # Calling graph using the access token
        graph_data = requests.get(  # Use token to call downstream service
            config["endpoint"],
            headers={'Authorization': 'Bearer ' + result['access_token']},).json()
        print("Graph API call result: %s" % json.dumps(graph_data, indent=2))
    
    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))  # You may need this when reporting a bug
    

    日志输出:

    DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): graph.microsoft.com:443
    DEBUG:urllib3.connectionpool:https://graph.microsoft.com:443 "GET /v1.0/users HTTP/1.1" 403 None
    
    Graph API call result: {
      "error": {
        "code": "Authorization_RequestDenied",
        "message": "Insufficient privileges to complete the operation.",
        "innerError": {
          "date": "2022-11-06T13:07:13",
          "request-id": "13a2593f-e9c9-4844-aca5-7c362a7f83b8",
          "client-request-id": "13a2593f-e9c9-4844-aca5-7c362a7f83b8"
        }
      }
    }
    

    我使用的代码有问题吗?或者Microsoft Graph中是否有其他设置需要由拥有组织设置?还是另一个问题?

    再次感谢您的帮助。

    0 回复  |  直到 4 年前
        1
  •  3
  •   Glen Scales    4 年前

    问题是您试图使用客户端凭据流,但您的所有权限都是对该流无效的委派权限。你需要将应用程序权限和同意分配给他们,例如

    enter image description here

    默认情况下,这将允许您访问租户中的每个邮箱,正如您所提到的,如果您只想访问一个邮箱,则可以缩小权限范围 https://learn.microsoft.com/en-us/graph/auth-limit-mailbox-access