我正在努力为我的Flask webapp获取Azure Active Directory用户身份验证。在尝试任何用户身份验证之前,它正在运行,但现在我已经按照我能找到的所有示例进行操作,而且我不知道我做错了什么。也许我完全走错了路,但如果有人能说出我做错了什么,我可以用一些反馈。它不会在本地主机上或在网站上运行。在网站上,我只收到500错误,请求超时。在本地主机上,它会给我签名请求,但之后它会返回错误。
我一步一步地遵循了这个文档:
https://github.com/Azure-Samples/active-directory-python-webapp-graphapi
我在Azure Active Directory中注册了我的webapp,并将App IDU URI设置为:
HTTPS:// {company_domain.com} / {APPNAME}
主页网址:
HTTPS:// {APPNAME} .azurewebsites.net
回复网址:
HTTPS:// {APPNAME} .azurewebsites.net
允许委派权限“登录并读取用户配置文件”所需的权限
在我的代码中,我创建了一个如下所示的config.py文件:
RESOURCE = "https://{app_name}.azurewebsites.net"
TENANT = "{company_domain_name.com}"
AUTHORITY_HOST_URL = "https://login.microsoftonline.com"
CLIENT_ID = "{client_id}" # copy the Application ID of your app from your Azure portal
CLIENT_SECRET = "{client_secret_key}" # copy the value of key you generated when setting up the application
然后在我的init.py文件中,我有以下代码:
from flask import Flask, render_template, Response, session, request, url_for, redirect
import adal
import config
import requests
import uuid
AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT
REDIRECT_URI = 'https://{appname}.azurewebsites.net/getAtoken'
TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' +
'response_type=code&client_id={}&redirect_uri={}&' +
'state={}&resource={}')
@app.route("/")
def main():
login_url = 'http://<app_name>.azurewebsites.net/login'
resp = Response(status=307)
resp.headers['location'] = login_url
return resp
@app.route("/login")
def login():
auth_state = str(uuid.uuid4())
session['state'] = auth_state
authorization_url = TEMPLATE_AUTHZ_URL.format(
config.TENANT,
config.CLIENT_ID,
REDIRECT_URI,
auth_state,
config.RESOURCE)
resp = Response(status=307)
resp.headers['location'] = authorization_url
return resp
@app.route("/getAToken")
def main_logic():
code = request.args['code']
state = request.args['state']
if state != session['state']:
raise ValueError("State does not match")
auth_context = adal.AuthenticationContext(AUTHORITY_URL)
token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, config.RESOURCE,
config.CLIENT_ID, config.CLIENT_SECRET)
Flask.session['access_token'] = token_response['accessToken']
return Flask.redirect('/index')
@app.route('/index')
def index():
if 'access_token' not in session:
return redirect(url_for('login'))
endpoint = config.RESOURCE + '/' + config.API_VERSION + '/me/'
http_headers = {'Authorization': session.get('access_token'),
'User-Agent': 'adal-python-sample',
'Accept': 'application/json',
'Content-Type': 'application/json',
'client-request-id': str(uuid.uuid4())}
return render_template('index.html')
在本地主机上,它会给我签名请求,但之后它会返回错误。
它表示回复网址不匹配。您可以为已注册的Azure AD WebApp添加回复URL(http://localhost:5000/getAToken)。如果要在本地和azure平台上运行它,可以在回复URL中添加两者。
在本地测试
在网站上,我只收到500错误,请求超时
似乎WebApp没有正确开发。有关如何在Azure App Service上设置Python环境的更多信息,请参阅此tutorial。