[Python] How to protect Python Flask Blueprints pages with Azure authentication

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have got an app which authenticate using Azure AD. If I browse to / or /page then it prompts to login, how do I protect other pages/blueprints i.e. profile page?

    app.py

    import os
    import requests
    from flask import Flask, render_template
    from identity.flask import Auth
    import app_config
    from profile import profile_page

    app = Flask(__name__)

    app.register_blueprint(profile_page)

    app.config.from_object(app_config)
    auth = Auth(
    app,
    authority=os.getenv("AUTHORITY"),
    client_id=os.getenv("CLIENT_ID"),
    client_credential=os.getenv("CLIENT_SECRET"),
    redirect_uri=os.getenv("REDIRECT_URI"),
    oidc_authority=os.getenv("OIDC_AUTHORITY"),
    b2c_tenant_name=os.getenv("B2C_TENANT_NAME"),
    b2c_signup_signin_user_flow=os.getenv("SIGNUPSIGNIN_USER_FLOW"),
    b2c_edit_profile_user_flow=os.getenv("EDITPROFILE_USER_FLOW"),
    b2c_reset_password_user_flow=os.getenv("RESETPASSWORD_USER_FLOW"),
    )

    @app.route("/")
    @auth.login_required(scopes=os.getenv("SCOPE", "").split())
    def index(*, context):
    api_result1 = (
    requests.get( # Use access token to call a web api
    os.getenv("ENDPOINT"),
    headers={"Authorization": "Bearer " + context["access_token"]},
    timeout=30,
    ).json()
    if context.get("access_token")
    else "Did you forget to set the SCOPE environment variable?"
    )

    ##
    return render_template(
    "index.html",
    user=context["user"],
    edit_profile_url=auth.get_edit_profile_url(),
    api_endpoint=os.getenv("ENDPOINT"),
    title=f"Flask Web App Sample v{__version__}",
    )

    @app.route("/page1")
    @auth.login_required
    def page1(*, context):
    test = "hello test app.py"
    return render_template("page1.html", test=test)

    if __name__ == "__main__":
    app.run(debug=True)


    profile.py

    from flask import Flask, render_template, flash, redirect, url_for, request, Blueprint
    import requests

    profile_page = Blueprint("profile", __name__)


    @profile_page.route("/profile")
    def profile():
    test = "hello from profile.py"
    return render_template("profile.html", test=test)



    I have tried adding @auth.login_required after @profile_page.route("/profile") but it complains about app not defined in profile page.

    Any help on this would be much appreciated, thank you.

    Continue reading...

Compartilhe esta Página