ひさふぃの日記

DjangoとPythonとLaravelが好き。大阪でフリーランスエンジニアやってます。

AzureADのsamlシングルサインオンをonelogin/python3-samlで試す|idP-Initiated

この記事で書くこと

役に立った

SAMLの概要がわかる神動画
https://www.youtube.com/watch?v=SvppXbpv-5k
SAMLのリクエストとレスポンスの内容を開発者ツールで表示してくれる神ツール
https://chrome.google.com/webstore/detail/saml-chrome-panel/paijfdbeoenhembfhkhllainmocckace

idP:AzureADの設定

AzureADのシングルサインオン設定方法(公式)
https://docs.microsoft.com/ja-jp/azure/active-directory/manage-apps/configure-single-sign-on-non-gallery-applications
まずは手順1のみ
値の設定は下記2箇所

基本的な SAML 構成
識別子 (エンティティ ID) => https://localhost/metadata/
応答 URL (Assertion Consumer Service URL) => https://localhost/?acs

ちなみに新たにアプリを設定するときは「エンタープライズ アプリケーション」から作成してください
「アプリの登録」ではないので注意!

SP:python3-samlの設定

SP側にシングルサインオンを実装できるライブラリを使います
https://github.com/onelogin/python3-saml
今回は上記ライブラリを手軽に試せるdockerがありますので併せて活用します(宣伝)
https://github.com/hisafi/docker

git clone git@github.com:hisafi/docker.git
cd flask_python3-saml
git clone https://github.com/onelogin/python3-saml.git  
docker-compose up -d

idPとSPを連携

python3-samlの設定ファイルにAzureADの設定値を記載していきます
今回はflaskのデモを用いているので記載するファイルは下記になります
/python3-saml/demo-flask/saml/setting.json

"sp": {
    "entityId": "https://<sp_domain>/metadata/",
    "assertionConsumerService": {
        "url": "https://<sp_domain>/?acs",
        "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    },
    "singleLogoutService": {
        "url": "https://<sp_domain>/?sls",
        "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
    },

"<sp_domain>"を"localhost"へ変更

"idp": {
    ...,
    "x509cert": "<onelogin_connector_cert>"
}

公式手順3に記載のbase64エンコードされた証明書の文字列を上記に設定
https://docs.microsoft.com/ja-jp/azure/active-directory/manage-apps/configure-single-sign-on-non-gallery-applications

"idp": {
    "entityId": "https://app.onelogin.com/saml/metadata/<onelogin_connector_id>",
    "singleSignOnService": {
        "url": "https://app.onelogin.com/trust/saml2/http-post/sso/<onelogin_connector_id>",
        ...
    },
    "singleLogoutService": {
        "url": "https://app.onelogin.com/trust/saml2/http-redirect/slo/<onelogin_connector_id>",
        ...
    },

公式手順4の箇所を参照して上記の値を設定
https://docs.microsoft.com/ja-jp/azure/active-directory/manage-apps/configure-single-sign-on-non-gallery-applications

接続確認

https://localhostに接続してログインボタンを押す!!

Azure定番システム設計・実装・運用ガイド