我正在尝试使用 Flask 编写我的第一个 Web 应用程序并针对 Azure AD 进行身份验证。似乎进行身份验证的最简单方法是 ms-identity-web 模块。我在网上找到了这个示例和教程: ms-identity-python-flask-webapp-身份验证
一切看起来都很好,我遇到的唯一问题是 client_credential。 ms-identity-web 需要一个字符串(客户端密钥),但就我而言,我需要使用证书。我已生成公钥/私钥并将公钥上传到天蓝色注册的应用程序。我能够使用 MSAL 的私钥进行身份验证,但找不到使用 ms-identity-web 进行身份验证的方法。示例代码中有一个 json 配置文件,它有一个名为“client_secret”的键。我尝试传递字典作为该元素的值,但它不起作用。感谢有关如何将私钥作为 client_credential 传递的任何提示。
"client_credential": {
"thumbprint": "450504A...",
"private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
}
我知道我可以使用 MSAL 或 azure.identity 或其他模块来完成此操作,并且我知道 ms-identity-web 只是 MSAL 和 azure.identity 的包装器,但我很好奇如何使用此特定模块来完成此操作。
我知道我可以使用 MSAL 或 azure.identity 或其他模块来完成,并且我知道 ms-identity-web 只是 MSAL 和 azure.identity 的包装器,但我很好奇如何使用这个特定模块来完成此任务。
或者,我们可以考虑直接在 Flask 应用中使用 MSAL 库来处理使用客户端证书的身份验证。正如您提到的,您可以使用带有私钥的 MSAL 进行身份验证,因此这可能是一种可行的方法。您仍然可以在 Web 应用程序中利用 Flask,并单独使用 MSAL 进行身份验证。
代码:
import logging
from flask import Flask, current_app, render_template, redirect, url_for, request
from flask_session import Session
from pathlib import Path
import app_config
from ms_identity_web import IdentityWebPython
from ms_identity_web.adapters import FlaskContextAdapter
from ms_identity_web.errors import NotAuthenticatedError
from ms_identity_web.configuration import AADConfig
def create_app():
app = Flask(__name__, root_path=Path(__file__).parent)
app.config.from_object(app_config)
Session(app)
app.register_error_handler(NotAuthenticatedError, lambda err: (render_template('auth/401.html'), err.code))
aad_configuration = AADConfig.parse_json('aad.config.json')
app.logger.level = logging.INFO
if app.config.get('ENV') == 'production':
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
aad_configuration.client.client_certificate = {
"path": "path/to/certificate.pem",
"thumbprint": "<CERT_THUMBPRINT>"
}
AADConfig.sanity_check_configs(aad_configuration)
adapter = FlaskContextAdapter(app)
ms_identity_web = IdentityWebPython(aad_configuration, adapter)
@app.route('/')
@app.route('/sign_in_status')
def index():
return render_template('auth/status.html')
@app.route('/token_details')
@ms_identity_web.login_required
def token_details():
current_app.logger.info("token_details: user is authenticated, will display token details")
return render_template('auth/token.html')
return app
if __name__ == '__main__':
app=create_app()
app.run(ssl_context='adhoc')
app=create_app()
config.json:
"client": {
"client_id": "your_client_id",
"client_credential": {
"path": "path/to/certificate.pem",
"thumbprint": "<CERT_THUMBPRINT>"
}
msal.ConfidentialClientApplication
类通过客户端证书进行身份验证。重定向:
登录状态: