Microsoft Graph 身份验证

2024-03-14

我正在用 Python 构建一个应用程序,它可以从 Azure AD 检索数据。此数据可能需要应用程序权限或委派权限。我成功检索了仅需要应用程序权限的数据。但是,为了检索需要委托权限的数据,我尝试使用 OAuth2。是否可以使用 OAuth2 通过 Microsoft Graph 进行身份验证,但不让用户使用网页登录,而是通过 Python 脚本本身提供用户凭据?

注意:我想使用 Microsoft Graph API(v1.0 和 beta)而不是 Azure AD Graph API。


假设您已注册并配置(api 权限)您的 azure 应用程序,并且已复制应用程序“客户端 ID”和“客户端密钥”,您可以定义一个保存会话的类。 以下代码适用于我的应用程序:

import json
import requests
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient


class SharepointSession(object):
    """ Base Class without credentials, use real credentials in derived Classes
    or instances
    """
    api_uri = "https://graph.microsoft.com"
    api_version = "v1.0"
    scope = ["https://graph.microsoft.com/.default"]
    directory_id = ""  # - tenant id
    token_url = "https://login.microsoftonline.com/{}/oauth2/v2.0/token"
    sites_url = "{}/{}/sites".format(api_uri, api_version)
    site = document_name = app_name = client_id = client_secret = ""
    site_id = None
    doc_id = None

    def __init__(self):
        """  """

    def getTokenizedSession(self):
        """
        OAuth2 to get access token
        First set up a backend client, mind to set grant_type
        build a OAuth2 Session with the client
        get access token

        Mind: python 3.x oauthlib requires scope params on more calls than py 2.x
        """
        client = BackendApplicationClient(
            client_id=self.client_id, scope=self.scope, grant_type="client_credentials")

        session = OAuth2Session(client=client, scope=self.scope)
        # fill access token
        token = session.fetch_token(token_url=self.token_url.format(self.directory_id),
                                    client_id=self.client_id,
                                    scope=self.scope,
                                    client_secret=self.client_secret)
        self.session = session
        self.token = token
        return session, token

    def getSiteId(self):
        # get the site id
        ae = "{}/myonline.sharepoint.com:/sites/{}:".format(
            self.sites_url, self.site)
        rt = self.session.get(ae)
        response = json.loads(rt.text)
        self.site_id = response.get("id")
        return self.site_id

    def someOtherMethod(self):
        """         ...             """

现在,您可以使用从 azure 应用程序注册复制的凭据实例化会话类,即“目录 id”(与租户 id 相同)、“客户端 id”和“客户端密钥” 像这样:

mysp_session = SharepointSession()
mysp_session.directory_id = "XXXXXXXX-XXXX-YYYY-ZZZZ-XXXXXXXXX"
mysp_session.site = "MySitename"
mysp_session.document_name = "Testlist"
mysp_session.client_id = r"xxxxxxxxxxxxxxxxxxxxxxx"
mysp_session.client_secret = r"xxxxxxxxxxxxxxxxxxxxxxx"

# connect 
session, token = mysp_session.getTokenizedSession()

# do your business logic
mysp_session.getSiteId()
....
mysp_session.someOtherMethod()

希望有帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Microsoft Graph 身份验证 的相关文章

随机推荐