【问题标题】:Query on Microsoft Graph API Python在 Microsoft Graph API Python 上查询
【发布时间】:2022-11-10 18:30:53
【问题描述】:

我想使用 python 从客户端收件箱中通过 Graph API 提取电子邮件。 我从一个教程开始,并成功地在我的个人收件箱上进行了试验。

我的问题, 每次我的代码生成一个授权 URL。 我必须浏览它(使用网络浏览器库),使用我的凭据登录并复制粘贴授权代码以生成访问令牌。 每次都是大量的手工工作。

问题 : 有没有办法自动化令牌生成的整个过程? 这样我的客户只共享他的应用程序 ID 和客户秘密,并且在没有他的登录凭据的情况下提取电子邮件?

我的代码附在下面 -


import msal 
from msal import PublicClientApplication 
import webbrowser
import requests
import pandas as pd


APPLICATION_ID="app id"
CLIENT_SECRET="client secret"
authority_url='https://login.microsoftonline.com/common/'
base_url = 'https://graph.microsoft.com/v1.0/'
endpoint_url = base_url+'me'
SCOPES = ['Mail.Read','Mail.ReadBasic']


client_instance = msal.ConfidentialClientApplication(client_id = APPLICATION_ID,client_credential = CLIENT_SECRET,authority = authority_url)
authorization_request_url=client_instance.get_authorization_request_url(SCOPES)
#print(authorization_request_url)

# browsing authorization request URL for retrieving authorization code.   
webbrowser.open(authorization_request_url,new=True)

# Manually pasting authorization code.
authorization_code='authorization code from authorization URL'  

access_token = client_instance.acquire_token_by_authorization_code(code=authorization_code,scopes=SCOPES)

access_token_id=access_token['access_token']

# Rest of the codes are for hitting the end point and retrieving the messages

任何有关代码建议的帮助将不胜感激。

提前致谢

【问题讨论】:

    标签: python-3.x microsoft-graph-api msal msgraph


    【解决方案1】:

    如果您只想使用 clientId 和 clientSecret 进行身份验证,而不需要任何用户上下文,则应利用 client credentials 流。

    您可以查看this 官方 MS 示例,该示例使用相同的 MSAL 库来处理客户端凭据流。这很简单,如下所示:

    import sys  # For simplicity, we'll read config file from 1st CLI param sys.argv[1]
    import json
    import logging
    
    import requests
    import msal
    
    
    # Optional logging
    # logging.basicConfig(level=logging.DEBUG)
    
    config = json.load(open(sys.argv[1]))
    
    # 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"],
        # token_cache=...  # Default cache is in memory only.
                           # You can learn how to use SerializableTokenCache from
                           # https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
        )
    
    # 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)
    
    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"])
    
    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: ")
        print(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
    

    该示例正在从 MS Graph 中检索用户列表,但应该只是通过将 parameters.json 文件中的“endpoint”参数更改为来调整它以检索特定用户的电子邮件列表:

    "endpoint": "https://graph.microsoft.com/v1.0/users//users/{id | userPrincipalName}/messages" 
    

    您可以查看here 有关 MS Graph 请求列出电子邮件的更多信息。

    【讨论】:

      【解决方案2】:

      注册您的应用 从 azure 门户获取您的租户 ID 并禁用 mfa

      application_id = "xxxxxxxxxx"
      client_secret = "xxxxxxxxxxxxx"
      #authority_url = "xxxxxxxxxxx"
      authority_url = 'xxxxxxxxxxxxxxxxxxxx'
      base_url = "https://graph.microsoft.com/v1.0/"
      endpoint = base_url+"me"
      scopes = ["User.Read"]
      tenant_id = "xxxxxxxxxxxx"
      token_url = 'https://login.microsoftonline.com/'+tenant_id+'/oauth2/token'
      
      token_data = {
      'grant_type': 'password',
      'client_id': application_id,
      'client_secret': client_secret,
      'resource': 'https://graph.microsoft.com',
      'scope':'https://graph.microsoft.com',
      'username':'xxxxxxxxxxxxxxxx',  # Account with no 2MFA
      'password':'xxxxxxxxxxxxxxxx',
      }
      token_r = requests.post(token_url, data=token_data)
      token = token_r.json().get('access_token')
      print(token)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-10
        • 2021-12-06
        • 1970-01-01
        • 2018-06-16
        • 2021-11-20
        相关资源
        最近更新 更多