英文:
How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?
问题
以下是您提供的内容的中文翻译:
我在一个 Web 应用程序中使用以下示例,该示例通过 Azure AD 对用户进行身份验证。当输入 URL http://127.0.0.1:5000/unprotected 时,我正确地看到
你好,世界
但输入 http://127.0.0.1:5000/protected 会产生
{"errors": [{"id": "***", "status": 401, "title": "缺少授权标头", "detail": "确保您的请求包括一个 'Authorization' 标头,然后重试"}]}
是否可以修改代码,以便用户被重定向到登录页面,并在登录后看到正确的网站,显示 "你好,经过身份验证和授权的实体"?
# https://pypi.org/project/flask-azure-oauth/
from flask import Flask
from flask_azure_oauth import FlaskAzureOauth
app = Flask(__name__)
app.config['AZURE_OAUTH_TENANCY'] = '***'
app.config['AZURE_OAUTH_APPLICATION_ID'] = '***'
auth = FlaskAzureOauth()
auth.init_app(app)
@app.route('/unprotected')
def unprotected():
return '你好,世界'
@app.route('/protected')
@auth()
def protected():
return '你好,经过身份验证的实体'
@app.route('/protected-with-single-scope')
@auth('required-scope')
def protected_with_scope():
return '你好,经过身份验证和授权的实体'
@app.route('/protected-with-multiple-scopes')
@auth('required-scope1 required-scope2')
def protected_with_multiple_scopes():
return '你好,经过身份验证和授权的实体'
if __name__ == '__main__':
app.run(debug=True)
英文:
I use below example for a web-app which authenticates the User via Azure AD. When entering URL http://127.0.0.1:5000/unprotected I correctly see
> hello world
but entering http://127.0.0.1:5000/protected yields
> {"errors": [{"id": "***", "status": 401, "title": "Missing
> authorization header", "detail": "Ensure your request includes an
> 'Authorization' header and try again"}]}
Is it possible to modify the code so that the user is redirected to a login-page and after logged in sees the correct site showing "hello authenticated and authorised entity"?
# https://pypi.org/project/flask-azure-oauth/
from flask import Flask
from flask_azure_oauth import FlaskAzureOauth
app = Flask(__name__)
app.config['AZURE_OAUTH_TENANCY'] = '***'
app.config['AZURE_OAUTH_APPLICATION_ID'] = '***'
auth = FlaskAzureOauth()
auth.init_app(app)
@app.route('/unprotected')
def unprotected():
return 'hello world'
@app.route('/protected')
@auth()
def protected():
return 'hello authenticated entity'
@app.route('/protected-with-single-scope')
@auth('required-scope')
def protected_with_scope():
return 'hello authenticated and authorised entity'
@app.route('/protected-with-multiple-scopes')
@auth('required-scope1 required-scope2')
def protected_with_multiple_scopes():
return 'hello authenticated and authorised entity'
if __name__ == '__main__':
app.run(debug=True)
答案1
得分: 0
您可以按照此MS文档来使用Python(Flask应用程序)通过用户身份登录。
代码:
import identity.web
import requests
from flask import Flask, redirect, render_template, request, session, url_for
from flask_session import Session
import app_config
__version__ = "0.7.0"
app = Flask(__name__)
app.config.from_object(app_config)
assert app.config["REDIRECT_PATH"] != "/", "REDIRECT_PATH must not be /"
Session(app)
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
auth = identity.web.Auth(
session=session,
authority=app.config["AUTHORITY"],
client_id=app.config["CLIENT_ID"],
client_credential=app.config["CLIENT_SECRET"],
)
@app.route("/login")
def login():
return render_template("login.html", version=__version__, **auth.log_in(
scopes=app_config.SCOPE, # Have user consent to scopes during log-in
redirect_uri=url_for("auth_response", _external=True), # Optional. If present, this absolute URL must match your app's redirect_uri registered in Azure Portal
))
@app.route(app_config.REDIRECT_PATH)
def auth_response():
result = auth.complete_log_in(request.args)
if "error" in result:
return render_template("auth_error.html", result=result)
return redirect(url_for("index"))
@app.route("/logout")
def logout():
return redirect(auth.log_out(url_for("index", _external=True)))
@app.route("/")
def index():
if not (app.config["CLIENT_ID"] and app.config["CLIENT_SECRET"]):
# This check is not strictly necessary.
# You can remove this check from your production code.
return render_template('config_error.html')
if not auth.get_user():
return redirect(url_for("login"))
return render_template('index.html', user=auth.get_user(), version=__version__)
if __name__ == "__main__":
app.run()
用户将被重定向到登录页面,登录后将看到正确的站点显示“hello authenticated and authorised entity”。
登录后,如果需要在您的站点上显示“hello authenticated and authorised entity”,您可以将该句插入到您的index.html中。
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Web App: Index</title>
</head>
<body>
<h1>Sample Web App</h1>
<h2>Welcome {{ user.get("name") }}!</h2>
<h3>Hello authenticated and authorised entity</h3>
<ul>
<li><a href="/logout">Logout</a></li>
</ul>
</body>
</html>
输出:
英文:
You can follow this MS-Document to log in with the user using identity by Python(Flask app).
Code:
import identity.web
import requests
from flask import Flask, redirect, render_template, request, session, url_for
from flask_session import Session
import app_config
__version__ = "0.7.0"
app = Flask(__name__)
app.config.from_object(app_config)
assert app.config["REDIRECT_PATH"] != "/", "REDIRECT_PATH must not be /"
Session(app)
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
auth = identity.web.Auth(
session=session,
authority=app.config["AUTHORITY"],
client_id=app.config["CLIENT_ID"],
client_credential=app.config["CLIENT_SECRET"],
)
@app.route("/login")
def login():
return render_template("login.html", version=__version__, **auth.log_in(
scopes=app_config.SCOPE, # Have user consent to scopes during log-in
redirect_uri=url_for("auth_response", _external=True), # Optional. If present, this absolute URL must match your app's redirect_uri registered in Azure Portal
))
@app.route(app_config.REDIRECT_PATH)
def auth_response():
result = auth.complete_log_in(request.args)
if "error" in result:
return render_template("auth_error.html", result=result)
return redirect(url_for("index"))
@app.route("/logout")
def logout():
return redirect(auth.log_out(url_for("index", _external=True)))
@app.route("/")
def index():
if not (app.config["CLIENT_ID"] and app.config["CLIENT_SECRET"]):
# This check is not strictly necessary.
# You can remove this check from your production code.
return render_template('config_error.html')
if not auth.get_user():
return redirect(url_for("login"))
return render_template('index.html', user=auth.get_user(), version=__version__)
if __name__ == "__main__":
app.run()
> User is redirected to a login page and after logging in sees the correct site showing "hello authenticated and authorised entity.
After logging in, if you need to show the "hello authenticated and authorised entity" on your site. you can insert the sentence into your index.html.
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Web App: Index</title>
</head>
<body>
<h1>Sample Web App</h1>
<h2>Welcome {{ user.get("name") }}!</h2>
<h3>Hello authenticated and authorised entity</h3>
<ul>
<li><a href="/logout">Logout</a></li>
</ul>
</body>
</html>
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论