Python Microsoft Graph API:我陷入授权工作流

Python Microsoft Graph API:我陷入授权工作流,python,azure-active-directory,microsoft-graph-api,Python,Azure Active Directory,Microsoft Graph Api,我正在尝试从我创建的Azure Active Directory获取数据。 我想通过Microsoft的Graph API检索此数据。我使用了Microsoft提供的一个代码示例来发出HTTP GET请求: Config.py文件: """Configuration settings for running the Python auth samples locally. In a production deployment, this information should be saved

我正在尝试从我创建的Azure Active Directory获取数据。 我想通过Microsoft的Graph API检索此数据。我使用了Microsoft提供的一个代码示例来发出HTTP GET请求:

Config.py文件:

"""Configuration settings for running the Python auth samples locally.

In a production deployment, this information should be saved in a database or
other secure storage mechanism.
"""


CLIENT_ID = 'Here I Pasted my application ID'

CLIENT_SECRET = 'Here I Pasted the key i generated'

REDIRECT_URI = 'http://localhost:5000/login/authorized'

# AUTHORITY_URL ending determines type of account that can be authenticated:
# /organizations = organizational accounts only
# /consumers = MSAs only (Microsoft Accounts - Live.com, Hotmail.com, etc.)
# /common = allow both types of accounts
AUTHORITY_URL = 'https://login.microsoftonline.com/common'

AUTH_ENDPOINT = '/oauth2/v2.0/authorize'
TOKEN_ENDPOINT = '/oauth2/v2.0/token'

RESOURCE = 'https://graph.microsoft.com/'
API_VERSION = 'v1.0'
SCOPES = ['User.Read.All'] # Add other scopes/permissions as needed.


# This code can be removed after configuring CLIENT_ID and CLIENT_SECRET above.
if 'ENTER_YOUR' in CLIENT_ID or 'ENTER_YOUR' in CLIENT_SECRET:
    print('ERROR: config.py does not contain valid CLIENT_ID and CLIENT_SECRET')
    import sys
    sys.exit(1)
示例_requests.py文件:

"""Requests-OAuthlib sample for Microsoft Graph """
# Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
# See LICENSE in the project root for license information.
import os
import uuid

import bottle
import requests_oauthlib

import config

MSGRAPH = requests_oauthlib.OAuth2Session(config.CLIENT_ID,
                                          scope=config.SCOPES,
                                          redirect_uri=config.REDIRECT_URI)

# Enable non-HTTPS redirect URI for development/testing.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Allow token scope to not match requested scope. (Other auth libraries allow
# this, but Requests-OAuthlib raises exception on scope mismatch by default.)
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
os.environ['OAUTHLIB_IGNORE_SCOPE_CHANGE'] = '1'

bottle.TEMPLATE_PATH = ['./static/templates']

@bottle.route('/')
@bottle.view('homepage.html')
def homepage():
    """Render the home page."""
    return {'sample': 'Requests-OAuthlib'}

@bottle.route('/login')
def login():
    """Prompt user to authenticate."""
    auth_base = config.AUTHORITY_URL + config.AUTH_ENDPOINT
    authorization_url, state = MSGRAPH.authorization_url(auth_base)
    MSGRAPH.auth_state = state
    return bottle.redirect(authorization_url)

@bottle.route('/login/authorized')
def authorized():
    """Handler for the application's Redirect Uri."""
    if bottle.request.query.state != MSGRAPH.auth_state:
        raise Exception('state returned to redirect URL does not match!')
    MSGRAPH.fetch_token(config.AUTHORITY_URL + config.TOKEN_ENDPOINT,
                        client_secret=config.CLIENT_SECRET,
                        authorization_response=bottle.request.url)
    return bottle.redirect('/graphcall')

@bottle.route('/graphcall')
@bottle.view('graphcall.html')
def graphcall():
    """Confirm user authentication by calling Graph and displaying some data."""
    endpoint = config.RESOURCE + config.API_VERSION + '/me'
    headers = {'SdkVersion': 'sample-python-requests-0.1.0',
               'x-client-SKU': 'sample-python-requests',
               'SdkVersion': 'sample-python-requests',
               'client-request-id': str(uuid.uuid4()),
               'return-client-request-id': 'true'}
    graphdata = MSGRAPH.get(endpoint, headers=headers).json()
    return {'graphdata': graphdata, 'endpoint': endpoint, 'sample': 'Requests-OAuthlib'}

@bottle.route('/static/<filepath:path>')
def server_static(filepath):
    """Handler for static files, used with the development server."""
    root_folder = os.path.abspath(os.path.dirname(__file__))
    return bottle.static_file(filepath, root=os.path.join(root_folder, 'static'))

if __name__ == '__main__':
    bottle.run(app=bottle.app(), server='wsgiref', host='localhost', port=5000)
“”“为Microsoft Graph请求OAuthlib示例”“”
#版权所有(c)微软。版权所有。根据麻省理工学院许可证授权。
#有关许可证信息,请参见项目根目录中的许可证。
导入操作系统
导入uuid
进口瓶
导入请求
导入配置
MSGRAPH=requests_oauthlib.OAuth2Session(config.CLIENT_ID,
scope=config.SCOPES,
重定向\u uri=config.redirect\u uri)
#为开发/测试启用非HTTPS重定向URI。
os.environ['OAUTHLIB\u unsecure\u TRANSPORT']=“1”
#允许令牌作用域与请求的作用域不匹配。(其他身份验证库允许
#这是错误的,但默认情况下,请求OAuthlib会在范围不匹配时引发异常。)
os.environ['OAUTHLIB\u RELAX\u TOKEN\u SCOPE']=“1”
os.environ['OAUTHLIB\u IGNORE\u SCOPE\u CHANGE']=“1”
battle.TEMPLATE_PATH=['./静态/模板']
@瓶子路径(“/”)
@瓶子视图('homepage.html')
def homepage():
“”“呈现主页。”“”
返回{'sample':'Requests OAuthlib'}
@瓶子路径(“/login”)
def login():
“”“提示用户进行身份验证。”“”
auth\u base=config.AUTHORITY\u URL+config.auth\u端点
授权url,state=MSGRAPH.authorization\u url(auth\u base)
MSGRAPH.auth_state=状态
返回瓶子。重定向(授权\u url)
@瓶子路径(“/login/authorized”)
def authorized():
“”“应用程序重定向Uri的处理程序。”“”
如果瓶子.request.query.state!=MSGRAPH.auth_状态:
引发异常('返回到重定向URL的状态不匹配!')
MSGRAPH.fetch_令牌(config.AUTHORITY_URL+config.token_端点,
client\u secret=config.client\u secret,
授权(响应=瓶子.请求.url)
返回瓶子。重定向(“/graphcall”)
@瓶子路径(“/graphcall”)
@视图('graphcall.html')
def graphcall():
“”“通过调用图形并显示一些数据来确认用户身份验证。”“”
endpoint=config.RESOURCE+config.API_VERSION+'/me'
headers={'SdkVersion':'sample-python-requests-0.1.0',
“x-client-SKU”:“示例python请求”,
“SdkVersion”:“示例python请求”,
“客户端请求id”:str(uuid.uuid4()),
'返回客户端请求id':'true'}
graphdata=MSGRAPH.get(endpoint,headers=headers).json()
返回{'graphdata':graphdata'endpoint':endpoint'sample':'Requests OAuthlib'}
@瓶子路径(“/static/”)
def服务器_静态(文件路径):
“”“与开发服务器一起使用的静态文件处理程序。”“”
root_folder=os.path.abspath(os.path.dirname(_文件__))
return battle.static_文件(filepath,root=os.path.join(root_文件夹,'static'))
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
运行(app=battle.app(),server='wsgiref',host='localhost',port=5000)
Github上的源代码

我收到以下问题。编译代码时,我转到端口5000上的本地主机:

然后我点击connect,它会带我进入登录界面。使用我的Microsoft帐户(与创建active directory和注册应用程序时使用的帐户相同)登录后,它只显示以下内容:

无论我是使用Azure帐户登录,还是使用我在active directory中创建的任何用户登录,它都不起作用

我的active directory只是一个名为staff的组,在该组中我有3个用户

如有任何评论,我将不胜感激


谢谢

“我们无法…”窗口的URL中有一个错误描述,你能添加吗?@juunas哦,对不起,当然可以。上面写着:你是在Azure Portal还是v2应用程序门户(apps.dev.microsoft.com)中注册了该应用程序?因为我看到您正在使用v2端点。目前您需要使用其他门户注册这些内容。@junnas with register您的意思是在active directory?中注册它,嗯,我是在azure门户的“应用注册”部分注册的,这就是我获得令牌的方式。或者我应该在你发给我链接的其他网站注册吗?是的,你需要使用其他网站。如果在Azure Portal中注册,则需要使用v1端点。