微软图形身份验证

Microsoft Graph Authentication(微软图形身份验证)
本文介绍了微软图形身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I’m building an application in Python which can retrieve data from Azure AD. This data can require either Application permissions or Delegated permissions. I had a success retrieving data which needs only Application permissions. However, in order to retrieve data which needs delegated permission, I am trying to use OAuth2. Is it possible to get authenticated with Microsoft Graph using OAuth2 but not having the user sign in using the web page, but instead supplying the user credentials through the Python script itself?

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

Note: I want to use Microsoft Graph API (v1.0 and beta) and not Azure AD Graph API.

推荐答案

假设您已注册并配置(api 权限)您的 azure 应用程序,并且您已复制应用程序client id"和client secret",您可以定义一个类举行你的会议.以下代码适用于我的应用:

Assuming you have registered and configured (api permissions) your azure app and you have copied the apps "client id" and "client secret" you can define a class that holds your session. The following code works for my app:

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"和客户端密码"像这样:

Now you can instantiate the session class with the credentials copied from your azure app registration i.e. "directory id" (same as tenant id), "client id" and "client secret" like this:

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()

希望对你有帮助

这篇关于微软图形身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)