How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?

huangapple go评论73阅读模式
英文:

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>

输出

How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?

How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?

英文:

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__ = &quot;0.7.0&quot;  
app = Flask(__name__)
app.config.from_object(app_config)
assert app.config[&quot;REDIRECT_PATH&quot;] != &quot;/&quot;, &quot;REDIRECT_PATH must not be /&quot;
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[&quot;AUTHORITY&quot;],
client_id=app.config[&quot;CLIENT_ID&quot;],
client_credential=app.config[&quot;CLIENT_SECRET&quot;],
)
@app.route(&quot;/login&quot;)
def login():
return render_template(&quot;login.html&quot;, version=__version__, **auth.log_in(
scopes=app_config.SCOPE, # Have user consent to scopes during log-in
redirect_uri=url_for(&quot;auth_response&quot;, _external=True), # Optional. If present, this absolute URL must match your app&#39;s redirect_uri registered in Azure Portal
))
@app.route(app_config.REDIRECT_PATH)
def auth_response():
result = auth.complete_log_in(request.args)
if &quot;error&quot; in result:
return render_template(&quot;auth_error.html&quot;, result=result)
return redirect(url_for(&quot;index&quot;))
@app.route(&quot;/logout&quot;)
def logout():
return redirect(auth.log_out(url_for(&quot;index&quot;, _external=True)))
@app.route(&quot;/&quot;)
def index():
if not (app.config[&quot;CLIENT_ID&quot;] and app.config[&quot;CLIENT_SECRET&quot;]):
# This check is not strictly necessary.
# You can remove this check from your production code.
return render_template(&#39;config_error.html&#39;)
if not auth.get_user():
return redirect(url_for(&quot;login&quot;))
return render_template(&#39;index.html&#39;, user=auth.get_user(), version=__version__)
if __name__ == &quot;__main__&quot;:
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:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;Sample Web App: Index&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Sample Web App&lt;/h1&gt;
&lt;h2&gt;Welcome {{ user.get(&quot;name&quot;) }}!&lt;/h2&gt;
&lt;h3&gt;Hello authenticated and authorised entity&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;/logout&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;

Output:

How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?

How to redirect User to login Screen when not logged in for a Flask App with Azure authorization?

huangapple
  • 本文由 发表于 2023年6月26日 20:43:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定