gpt4 book ai didi

python - Azure Python Flask应用程序-AD身份验证问题

转载 作者:行者123 更新时间:2023-11-28 17:58:51 26 4
gpt4 key购买 nike

解释起来可能有点复杂,所以我会尽力而为。

当前解决方案

我有一个 python Flask 应用程序,它将部署到 Azure 中的应用程序服务。我希望用户通过 Azure AD 身份验证登录到应用程序服务。为此,我使用 ADAL 库,因为我发现了一些可以实现此目的的代码。

我已针对 Azure AD 注册了应用程序,以便获取应用程序 ID 和应用程序 key 。为此,我使用了本教程:https://learn.microsoft.com/en-gb/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-redirect-uris-to-your-application

应用程序.py

import os
import urllib.parse
import uuid

import adal
import flask
import requests

import config
import logging

os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # enable non-HTTPS for testing

APP = flask.Flask(__name__, template_folder='static/templates')
APP.debug = True
APP.secret_key = 'development'
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

SESSION = requests.Session()

@APP.route('/')
def homepage():
"""Render the home page."""
logging.info('test')
logger.debug("test1")
return flask.render_template('homepage.html', sample='ADAL')

@APP.route('/login')
def login():
"""Prompt user to authenticate."""
auth_state = str(uuid.uuid4())
SESSION.auth_state = auth_state

# For this sample, the user selects an account to authenticate. Change
# this value to 'none' for "silent SSO" behavior, and if the user is
# already authenticated they won't need to re-authenticate.
prompt_behavior = 'select_account'

params = urllib.parse.urlencode({'response_type': 'code',
'client_id': config.CLIENT_ID,
'redirect_uri': config.REDIRECT_URI,
'state': auth_state,
'resource': config.RESOURCE,
'prompt': prompt_behavior})

return flask.redirect(config.AUTHORITY_URL + '/oauth2/authorize?' + params)

@APP.route('/login/authorized')
def authorized():
"""Handler for the application's Redirect Uri."""
code = flask.request.args['code']
auth_state = flask.request.args['state']
if auth_state != SESSION.auth_state:
raise Exception('state returned to redirect URL does not match!')
auth_context = adal.AuthenticationContext(config.AUTHORITY_URL, api_version=None)
token_response = auth_context.acquire_token_with_authorization_code(
code, config.REDIRECT_URI, config.RESOURCE, config.CLIENT_ID, config.CLIENT_SECRET)
SESSION.headers.update({'Authorization': f"Bearer {token_response['accessToken']}",
'User-Agent': 'adal-sample',
'Accept': 'application/json',
'Content-Type': 'application/json',
'SdkVersion': 'sample-python-adal',
'return-client-request-id': 'true'})
return flask.redirect('/graphcall')

@APP.route('/graphcall')
def graphcall():
"""Confirm user authentication by calling Graph and displaying some data."""
endpoint = config.RESOURCE + config.API_VERSION + '/me'
http_headers = {'client-request-id': str(uuid.uuid4())}
graphdata = SESSION.get(endpoint, headers=http_headers, stream=False).json()
return flask.render_template('graphcall.html',
graphdata=graphdata,
endpoint=endpoint,
sample='ADAL')

if __name__ == '__main__':
APP.run(debug=True)
APP.run()

配置.py

CLIENT_ID = 'd****************************'
CLIENT_SECRET = 'D******************************'
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'] # 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)

目前,当登录应用程序时,我会看到登录屏幕,我可以使用该屏幕登录,我认为已传递到我的组织密码屏幕进行登录。此后应用程序无法获取不记名 token 。然后将应用程序重定向回主页。

问题

  • 有没有一种方法可以让我不必对应用服务使用 Azure AD 授权,而无需使用 Azure AD 即可进行授权。
  • 更好的方法是什么?

或者我可以使用 Azure AD 进行身份验证,而无需使用 ADAL 库,并在登录我的 Flask 应用服务时使用内置的 Azure AD 授权。

我知道这可能无法很好地解释,因此如有任何疑问或更多信息,请告诉我

提前致谢。

最佳答案

如果我正确理解您的问题,您宁愿使用内置的 Azure AD 身份验证而不是 ADAL 库。

如果您只想使用登录功能,那么使用内置的 Azure AD 身份验证非常方便,无需修改代码。但如果你想获得访问 token ,你需要自己收集。

如何获取访问 token ?

从您的服务器代码中,特定于提供者的 token 被注入(inject)到 request header ,这样您就可以轻松访问它们。

App Service provides a built-in token store, which is a repository of tokens that are associated with the users of your web apps, but you must write code to collect, store, and refresh these tokens in your application.

更新:

enter image description here

关于python - Azure Python Flask应用程序-AD身份验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com