メインコンテンツにスキップ

すべてのアプリケーションからユーザーをサインアウトする

このガイドでは、1 つのリクエストで組織内のすべてのアプリケーションからユーザーをサインアウトする方法と、アプリケーションがサインアウトを検知して自身のセッションを終了できるようにする方法について説明します。


学習目標​

  • すべてのセッションまたは現在のセッションのみに対して SSO ログアウトエンドポイントを呼び出す方法。
  • アプリケーションでサインアウト通知を受信し検証する方法。
  • OpenID Connect (OIDC) バックチャネルログアウトトークンを取得する方法。
  • ユーザーがサインイン状態のままになる原因を見つける方法。

前提条件​


シングルサインアウトについて​

シングルサインアウトは、Casdoor 内のユーザーのセッションを終了し、アプリケーションにも同様の操作を行うよう指示します。一般的な用途は次のとおりです:

  • セキュリティインシデント: アカウントのすべてのセッションを一括で終了します。
  • 組織ポリシー: ユーザーが組織を離れたり役割を変更したりした際に、すべての場所からサインアウトします。
  • コンプライアンス: ユーザーがすべてのシステムからサインアウトされていることを保証します。
  • ユーザーのリクエスト: ユーザーが 1 つのアクションですべてのアプリケーションからサインアウトできるようにします。

logoutAll パラメーターにより、2 つのモードのいずれかを選択できます:

Full sign-out: logoutAll=true (default)Current session only: logoutAll=false
SessionsDeletes all sessions of the user across all applications of the organizationDeletes the current session
Access tokensExpires all access tokens issued to the userExpires the tokens that were issued in the current session
NotificationContains all session IDs and the hashes of all tokens of the userContains the current session ID and the hashes of all tokens of the user

ユーザーが 1 つのデバイスまたはブラウザでサインアウトし、他のデバイスやブラウザではサインイン状態を維持する場合、logoutAll=false を使用します。

このエンドポイントは、単一のクライアントが自身のセッション用に呼び出す標準的な OIDC エンドセッションエンドポイントである RP-initiated logout とは異なります。

SSO サインアウトエンドポイントを呼び出す​

GET or POST /api/sso-logout?logoutAll=<true|false>
ParameterRequiredDescription
logoutAllNotrue, 1, or omitted: sign out of all sessions. Any other value, such as false or 0: sign out of the current session only

リクエストをユーザーとして認証します。Authorization ヘッダーにアクセストークンを記載するか、セッションクッキーを使用します。認証方法の選択 を参照してください。

すべてのセッションからサインアウトします:

curl -X POST https://door.casdoor.com/api/sso-logout \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# Or explicitly specify logoutAll=true
curl -X POST "https://door.casdoor.com/api/sso-logout?logoutAll=true" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

現在のセッションのみからサインアウトします:

curl -X POST "https://door.casdoor.com/api/sso-logout?logoutAll=false" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

セッションクッキーで認証します:

curl -X POST https://door.casdoor.com/api/sso-logout \
--cookie "casdoor_session_id=abc123def456"

リクエストが成功すると、以下が返されます:

{
"status": "ok",
"msg": "",
"data": ""
}
FieldDescription
status"ok" on success, "error" on failure
msgError message on failure, otherwise empty
dataEmpty for this endpoint

アプリケーションからエンドポイントを呼び出す​

ブラウザ内で fetch を使用する場合:

// Logout from all sessions
fetch('https://door.casdoor.com/api/sso-logout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`
},
credentials: 'include'
})
.then(response => response.json())
.then(data => {
console.log('Logout successful:', data);
window.location.href = '/login';
})
.catch(error => {
console.error('Logout failed:', error);
});

// Logout from current session only
fetch('https://door.casdoor.com/api/sso-logout?logoutAll=false', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`
},
credentials: 'include'
})
.then(response => response.json())
.then(data => {
console.log('Logged out from current session:', data);
window.location.href = '/login';
});

Go SDK を使用する場合:

import "github.com/casdoor/casdoor-go-sdk/casdoorsdk"

func logout(w http.ResponseWriter, r *http.Request) {
// Get the access token from the session or request
token := getAccessTokenFromSession(r)

// Call the SSO logout endpoint
err := casdoorsdk.Logout(token)
if err != nil {
http.Error(w, "Logout failed", http.StatusInternalServerError)
return
}

// Clear local session
clearSession(w, r)

// Redirect to login page
http.Redirect(w, r, "/login", http.StatusFound)
}

JavaScript SDK を使用する場合:

import Sdk from "casdoor-js-sdk";

const CasdoorSDK = new Sdk({
serverUrl: "https://door.casdoor.com",
clientId: "YOUR_CLIENT_ID",
appName: "YOUR_APP_NAME",
organizationName: "YOUR_ORG_NAME",
});

async function handleLogout() {
try {
// Call the SSO logout endpoint
await CasdoorSDK.logout();

// Clear local state
localStorage.removeItem('casdoor_token');
sessionStorage.clear();

// Redirect to login page
window.location.href = '/login';
} catch (error) {
console.error('Logout failed:', error);
}
}

Python SDK を使用する場合:

from casdoor import CasdoorSDK

sdk = CasdoorSDK(
endpoint="https://door.casdoor.com",
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
certificate="YOUR_CERT",
org_name="YOUR_ORG_NAME",
app_name="YOUR_APP_NAME",
)

def logout(access_token):
try:
# Call the SSO logout endpoint
result = sdk.logout(access_token)

if result['status'] == 'ok':
# Clear local session
clear_session()
return True
else:
print(f"Logout failed: {result['msg']}")
return False
except Exception as e:
print(f"Logout error: {e}")
return False

リクエストの結果にかかわらず、その後にアプリケーションのローカル状態(保存されたトークン、キャッシュされたユーザー情報、ローカルセッションクッキー)をクリアしてください。ユーザーがサインアウトを選択した場合、Casdoor へのリクエストが失敗しても、ユーザーはサインアウト済みとして表示される必要があります。

async function logout() {
try {
await callSSOLogout();
} catch (error) {
console.error('SSO logout failed, clearing local state anyway:', error);
} finally {
// Always clear local state
clearLocalAuthenticationState();
redirectToLogin();
}
}

サインアウト通知を受信する​

サインアウト時、Casdoor はユーザーが登録したアプリケーションの各通知プロバイダーに通知を送信します。アプリケーションはこの通知を使用して、該当するユーザーの自社のセッションを終了します。

通知プロバイダーの設定​

  1. Casdoor の管理コンソールで 通知プロバイダー(例: Custom HTTP タイプ)を追加し、それをアプリケーションに追加します。

  2. Custom HTTP プロバイダーの場合、以下のフィールドを設定します:

    FieldValue
    EndpointEndpoint of your application that receives the notification, for example https://app.example.com/api/logout-webhook
    MethodPOST
    Parametercontent. This is the name of the form field that carries the JSON payload

通知を読み取る​

Casdoor は、以下のペイロードを含む POST リクエストを送信します:

{
"owner": "org-name",
"name": "username",
"displayName": "John Doe",
"email": "user@example.com",
"phone": "+1234567890",
"id": "user-id",
"event": "sso-logout",
"sessionIds": ["session-123", "session-456"],
"accessTokenHashes": ["hash-abc", "hash-def"],
"nonce": "random-nonce-xyz",
"timestamp": 1699900000,
"signature": "hmac-sha256-signature"
}
FieldDescription
sessionIdsIDs of the sessions that were ended
accessTokenHashesすべてのモードにおけるユーザーのアクセストークンの SHA-256 ハッシュ値(期限切れのトークンも含む)。logoutAll=false の場合、リストには有効なままとなる他のセッションのトークンも含まれるため、まず sessionIds で照合してください。アプリケーションが保持しているトークンのハッシュ値と比較して、終了すべきセッションを特定します
nonceRandom value that protects against replay
timestampUnix time at which Casdoor created the notification
signatureHMAC-SHA256 signature, computed with the client secret of the application

通知を検証する​

エンドポイントに到達できる人物なら誰でもリクエストを送信できます。通知に対応する前に:

  1. 署名を検証します。Go の場合:

    // Example verification in Go
    func verifyLogoutNotification(notification *SsoLogoutNotification, clientSecret string) bool {
    data := fmt.Sprintf("%s|%s|%s|%d|%s|%s",
    notification.Owner,
    notification.Name,
    notification.Nonce,
    notification.Timestamp,
    strings.Join(notification.SessionIds, ","),
    strings.Join(notification.AccessTokenHashes, ","))

    expectedSignature := hmacSHA256(clientSecret, data)
    return notification.Signature == expectedSignature
    }

    JavaScript の場合:

    // Example verification in JavaScript
    const crypto = require('crypto');

    function verifyLogoutNotification(notification, clientSecret) {
    const data = `${notification.owner}|${notification.name}|${notification.nonce}|${notification.timestamp}|${notification.sessionIds.join(',')}|${notification.accessTokenHashes.join(',')}`;

    const expectedSignature = crypto
    .createHmac('sha256', clientSecret)
    .update(data)
    .digest('hex');

    return notification.signature === expectedSignature;
    }
  2. 古すぎる通知(例えば 5 分以上前のもの)は拒否します:

    function isNotificationValid(notification) {
    const maxAge = 5 * 60 * 1000; // 5 minutes in milliseconds
    const now = Date.now();
    const notificationTime = notification.timestamp * 1000; // Convert to milliseconds

    if (now - notificationTime > maxAge) {
    console.error('Notification is too old, possible replay attack');
    return false;
    }

    return verifyLogoutNotification(notification, clientSecret);
    }
  3. sessionIds または accessTokenHashes に一致するアプリケーション内のセッションを終了します。

注意

クライアントシークレットは通知の署名に使用されます。環境変数やシークレットマネージャーなどサーバー側に保存し、クライアント側のコードに組み込まないでください。

OIDC バックチャネルログアウトトークンを受信する​

Casdoor supports OpenID Connect Back-Channel Logout 1.0. When a user's session ends, Casdoor sends a signed logout token to every application that has an active token for the user. Each application then ends its own session, server to server. Casdoor sends logout tokens when:

  • ユーザーは RP-initiated logout (/api/logout) を通じてサインアウトします。
  • どちらのモードでも、ユーザーは SSO ログアウトエンドポイント を通じてサインアウトします。
  • Max sessions 制限により、サインイン時に古いセッションが終了します。排他的サインイン を参照してください。通知されるのは、終了したセッションでサインインしていたアプリケーションのみです。
  • SAML サービスプロバイダーが シングルログアウト を開始します。通知されるのは、そのセッションでサインインしていたアプリケーションのみです。
  • 管理者または シンカー によって、ユーザーが禁止されるか削除されます。
  1. Casdoor 管理コンソールで、アプリケーションの編集ページを開きます。
  2. Backchannel logout URL (backchannelLogoutUri) を、ログアウトレットトークンを受信するアプリケーションのエンドポイントに設定します。

Casdoor は、logout_token パラメータを含む HTTP POST リクエストをその URI に送信します。トークンは、iss、sub、aud、iat、exp、jti クレームと http://schemas.openid.net/event/backchannel-logout イベントを持つ JSON Web Token (JWT) です。トークンは発行後 2 分で失効します。sid クレーム(Casdoor セッション ID)が含まれるのは、SSO ログアウトエンドポイント、セッション制限、および SAML シングルログアウトの場合のみです。/api/logout および禁止または削除されたユーザー向けに送信されるトークンには sid が含まれないため、sub で指定されたユーザーのすべてのセッションが終了します。バックチャネルログアウト URL が設定されていないアプリケーションはスキップされます。

SAML アプリケーションからのサインアウト​

SAML でユーザーをサインインさせるアプリケーションの場合、ユーザーがサインアウトすると、Casdoor は署名付き SAML LogoutRequest を、/api/sso-logout の両方のモードおよび /api/logout とともに、アプリケーションの SAML single logout URL に送信します。SAML サービスプロバイダーも Casdoor でログアウトを開始できます。Single logout を参照してください。

トラブルシューティング​

一部のアプリケーションにサインインしたままになる​

  • すべてのアプリケーションが Casdoor を通じてユーザーをサインインさせ、同じ組織に属していることを確認してください。
  • 各アプリケーションがすべてのリクエストでトークンを検証しているか、サインアウト通知に対応していることを確認してください。ローカルセッションのみを依存しているアプリケーションは、サインアウトを検知しません。

サインアウト後もトークンが有効な場合​

  • リクエストが /api/sso-logout に送られ、ユーザーとして認証されたことを確認してください。
  • アプリケーションがトークン検証の結果をキャッシュしていないことを確認してください。

サインアウト後、トークンレコードは ExpiresIn が 0 に設定されたままデータベースに残ります。トークンイントロスペクションエンドポイントとリフレッシュトークンエンドポイントはそれらを拒否します。そのようなリフレッシュトークンを使用するクライアントは、メッセージ "refresh token is expired" を伴うエラー invalid_grant を受け取ります。Casdoor が認識していないリフレッシュトークン(例えば リフレッシュトークンローテーション によって置き換えられたもの)は、"refresh token is invalid or revoked" で失敗します。

エンドポイントがエラーを返す場合​

StatusCauseWhat to do
HTTP 401The access token is invalid or expiredClear the local state and send the user to the sign-in page
HTTP 403The user isn't allowed to sign out. This points to a configuration problemCheck the configuration of the application
HTTP 500Error on the serverLog the error and clear the local state anyway
async function logout() {
try {
// Replace with your actual Casdoor server URL
const response = await fetch('https://door.casdoor.com/api/sso-logout', {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
});

if (!response.ok) {
console.error(`Logout failed with status: ${response.status}`);
// Clear local state anyway
}
} catch (error) {
console.error('Logout error:', error);
} finally {
clearLocalAuthenticationState();
redirectToLogin();
}
}

関連項目​