LoginSignup
1
2

Azure App ServiceでFlaskアプリケーションを公開する(with AAD認証)

Last updated at Posted at 2023-07-09

目的

ChatGPTアプリをFlaskで作成したので、Azure App Serviceに置きたくなった。
Azure App Serviceならではのハマりポイントがあったのでメモ程度に残しておく

Flask DanceでAAD認証する

とりあえず必要なパッケージをいろいろ設定する。

requirements.txt
openai
jinja2
flask
Flask-Dance

アプリケーションの作りはこんな感じ

※Flask自身はHTTPで動くためredirect_urlがhttp://~になってしまうため、
class ReverseProxiedを追加してHTTPSで動いていることをFlaskに伝えとく。
ここでかなりハマった。

app.py
from flask_dance.contrib.azure import make_azure_blueprint, azure

class ReverseProxied(object):
    def __init__(self, app):
        self.app = app
    def __call__(self, environ, start_response):
        scheme = environ.get('HTTP_X_FORWARDED_PROTO')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        return self.app(environ, start_response)

app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)
app.secret_key = "xxxxxxxx"

blueprint = make_azure_blueprint(
    client_id = "xxxxxxxx",
    client_secret = "xxxxxxxx",
    tenant = "xxxxxxxx",
)

app.register_blueprint(blueprint, url_prefix="/login")

@app.route("/", methods=["GET"])
def index():    
    if not azure.authorized:
        return redirect(url_for("azure.login"))
    resp = azure.get("/v1.0/me")
    assert resp.ok
    ##### 処理いろいろ #####
    return render_template("index.html")

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

Azure App Serviceの設定はこんな感じ
App Serviceはデフォルトでgunicorn経由でFlaskを動かすらしい。
image.png
スタートアップコマンド

gunicorn --bind=0.0.0.0 --timeout 600 app:app

AADへのアプリ登録は今のところ
image.png
image.png

完成したチャットアプリは今のところはこんな風
image.png

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2