Azure应用程序注册:Quickstart在Python中不起作用
我想要的:使用Flask与Azrue广告连接Python Web应用程序。我们正在使用Office 365和Azure 我尝试过的内容:我尝试过好几次,并从微软官方网站获得了教程。但是微软提出的快速启动代码对我来说并不适用。这是我使用过的教程。 ;; 发生了什么:每次我都可以登录。我通过“登录”按钮获取网页。单击后,我从Office 365获得典型的登录Wizzard。一切正常。但完成后,我回到了主页(登录网站)。我没有从FLASK那里得到日志文件?????正常情况下,一切都应该有效。我发现这取决于python中的session.get参数。但我不知道如何解决它 希望你能帮助我:) app.py:Azure应用程序注册:Quickstart在Python中不起作用,python,azure-active-directory,adal,msal,Python,Azure Active Directory,Adal,Msal,我想要的:使用Flask与Azrue广告连接Python Web应用程序。我们正在使用Office 365和Azure 我尝试过的内容:我尝试过好几次,并从微软官方网站获得了教程。但是微软提出的快速启动代码对我来说并不适用。这是我使用过的教程。 ;; 发生了什么:每次我都可以登录。我通过“登录”按钮获取网页。单击后,我从Office 365获得典型的登录Wizzard。一切正常。但完成后,我回到了主页(登录网站)。我没有从FLASK那里得到日志文件?????正常情况下,一切都应该有效。我发现这取
import uuid
import requests
from flask import Flask, render_template, session, request, redirect, url_for
from flask_session import Session # https://pythonhosted.org/Flask-Session
import msal
import app_config
app = Flask(__name__)
app.config.from_object(app_config)
Session(app)
@app.route("/")
def index():
if not session.get("user"):
return redirect(url_for("login"))
return render_template('index.html', user=session["user"], version=msal.__version__)
@app.route("/login")
def login():
session["state"] = str(uuid.uuid4())
# Technically we could use empty list [] as scopes to do just sign in,
# here we choose to also collect end user consent upfront
auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
return render_template("login.html", auth_url=auth_url, version=msal.__version__)
@app.route(app_config.REDIRECT_PATH) # Its absolute URL must match your app's redirect_uri set in AAD
def authorized():
if request.args.get('state') != session.get("state"):
return redirect(url_for("index")) # No-OP. Goes back to Index page
if "error" in request.args: # Authentication/Authorization failure
return render_template("auth_error.html", result=request.args)
if request.args.get('code'):
cache = _load_cache()
result = _build_msal_app(cache=cache).acquire_token_by_authorization_code(
request.args['code'],
scopes=app_config.SCOPE, # Misspelled scope would cause an HTTP 400 error here
redirect_uri=url_for("authorized", _external=True))
if "error" in result:
return render_template("auth_error.html", result=result)
session["user"] = result.get("id_token_claims")
_save_cache(cache)
return redirect(url_for("index"))
@app.route("/logout")
def logout():
session.clear() # Wipe out user and its token cache from session
return redirect( # Also logout from your tenant's web session
app_config.AUTHORITY + "/oauth2/v2.0/logout" +
"?post_logout_redirect_uri=" + url_for("index", _external=True))
@app.route("/graphcall")
def graphcall():
token = _get_token_from_cache(app_config.SCOPE)
if not token:
return redirect(url_for("login"))
graph_data = requests.get( # Use token to call downstream service
app_config.ENDPOINT,
headers={'Authorization': 'Bearer ' + token['access_token']},
).json()
return render_template('display.html', result=graph_data)
def _load_cache():
cache = msal.SerializableTokenCache()
if session.get("token_cache"):
cache.deserialize(session["token_cache"])
return cache
def _save_cache(cache):
if cache.has_state_changed:
session["token_cache"] = cache.serialize()
def _build_msal_app(cache=None, authority=None):
return msal.ConfidentialClientApplication(
app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
client_credential=app_config.CLIENT_SECRET, token_cache=cache)
def _build_auth_url(authority=None, scopes=None, state=None):
return _build_msal_app(authority=authority).get_authorization_request_url(
scopes or [],
state=state or str(uuid.uuid4()),
redirect_uri=url_for("authorized", _external=True))
def _get_token_from_cache(scope=None):
cache = _load_cache() # This web app maintains one cache per session
cca = _build_msal_app(cache=cache)
accounts = cca.get_accounts()
if accounts: # So all account(s) belong to the current signed-in user
result = cca.acquire_token_silent(scope, account=accounts[0])
_save_cache(cache)
return result
app.jinja_env.globals.update(_build_auth_url=_build_auth_url) # Used in template
if __name__ == "__main__":
app.run()
app_config.py:
import os
CLIENT_SECRET = "g3nK2F1DX4~_-0Mz-g.XXXXXXXXXXXX" # Our Quickstart uses this placeholder
# In your production app, we recommend you to use other ways to store your secret,
# such as KeyVault, or environment variable as described in Flask's documentation here
# https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables
# CLIENT_SECRET = os.getenv("CLIENT_SECRET")
# if not CLIENT_SECRET:
# raise ValueError("Need to define CLIENT_SECRET environment variable")
AUTHORITY = "https://login.microsoftonline.com/organizations" # For multi-tenant app
# AUTHORITY = "https://login.microsoftonline.com/Enter_the_Tenant_Name_Here"
CLIENT_ID = "ff68d6d9-d7a7-4433-a094-XXXXXXXXX"
REDIRECT_PATH = "/getAToken" # It will be used to form an absolute URL
# And that absolute URL must match your app's redirect_uri set in AAD
# You can find more Microsoft Graph API endpoints from Graph Explorer
# https://developer.microsoft.com/en-us/graph/graph-explorer
ENDPOINT = 'https://graph.microsoft.com/v1.0/users' # This resource requires no admin consent
# You can find the proper permission names from this document
# https://docs.microsoft.com/en-us/graph/permissions-reference
SCOPE = ["User.ReadBasic.All"]
SESSION_TYPE = "filesystem" # So token cache will be stored in server-side session
我也一直在努力解决这个问题,结果我的问题归结为没有正确安装requirements.txt文件中列出的包 我以前使用过flask_会话和一些身份验证库,因此在我使用的环境中已经安装了一些元素。我没有从repo中提供的requirements.txt进行安装,而是手动安装了丢失的包,并遇到了与您描述的相同的问题 在搜索github问题之后,我遇到了下面的线程,这表明在对其中一个依赖项进行更改之后,flask sessions包出现了问题 按照repo(安装flask session的分叉版本)安装要求后,样本按预期工作
希望这有帮助。不确定这是否适用,但可能会添加相关代码。谢谢您的评论。我添加了我在repo中使用的两个重要python文件。正如我在上面所写的,我的回购依赖于MS Quickstart回购。我知道粘贴(最少数量)源代码以演示问题是StackOverflow建议,但在这种情况下,从您关于“我在回购中使用的两个文件…[哪一个]依赖于MS Quickstart回购”的陈述中不清楚-无论您是否对其原始代码进行了任何修改。如果他们的回购协议无法开箱即用,您将有合法的理由在他们的github回购协议中创建一个问题。