0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Microsoftを使って ログイン認証 route.py

Last updated at Posted at 2025-05-28
route.py
@main.route("/ms_login")
def ms_login():
    session["state"] = str(uuid.uuid4())
    auth_url = _build_msal_app().get_authorization_request_url(
        SCOPE,
        state=session["state"],
        redirect_uri=url_for("main.ms_authorized", _external=True)
    )
    return redirect(auth_url)

@main.route(REDIRECT_PATH)
def ms_authorized():
    if request.args.get("state") != session.get("state"):
        return redirect(url_for("main.index"))

    if "error" in request.args:
        return f"エラー: {request.args['error_description']}"

    if "code" in request.args:
        result = _build_msal_app().acquire_token_by_authorization_code(
            request.args["code"],
            scopes=SCOPE,
            redirect_uri=url_for("main.ms_authorized", _external=True)
        )
        if "id_token_claims" in result:
            session["user"] = {
                "name": result["id_token_claims"].get("name"),
                "email": result["id_token_claims"].get("preferred_username")
            }
            return redirect(url_for("main.index"))

    return "Microsoftログイン失敗"

@main.route("/ms_logout")
def ms_logout():
    session.clear()
    return redirect(url_for("main.index"))

def _build_msal_app():
    return msal.ConfidentialClientApplication(
        CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET
    )

init.py

import msal
import uuid

client_id="あなたのクライアントID",
    client_secret="あなたのクライアントシークレット",
    AUTHORITY = "https://login.microsoftonline.com/common"
    scope=["User.Read"],
    redirect_url="/ms_authorized"
html
<a href="{{ url_for('main.ms_login') }}">Microsoftでログイン</a>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?