让用户退出所有应用
本指南介绍如何通过一个请求让用户退出组织下的所有应用,以及您的应用如何获知登出事件从而结束自身的会话。
学习目标
- 针对所有会话或仅当前会话调用 SSO 登出端点。
- 在应用中接收并验证登出通知。
- 接收 OpenID Connect (OIDC) 后端通道登出令牌。
- 排查用户保持登录状态的原因。
前提条件
- 使用 Casdoor 进行用户登录的应用。请参阅 Set up single sign-on。
- 以用户身份 向 Casdoor API 进行身份验证 的方法:访问令牌或会话 Cookie
- 若要接收通知:应用上需配置 notification provider
关于单点登出
单点登出会结束用户在 Casdoor 中的会话,并通知您的应用执行相同操作。典型用途包括:
- 安全事件:一次性结束账户的所有会话。
- 组织策略:当用户离开组织或角色变更时,在所有地方将其登出。
- 合规性:确保用户已从所有系统中登出。
- 用户请求:让用户通过一次操作退出所有应用。
logoutAll 参数选择以下两种模式之一:
Full sign-out: logoutAll=true (default) | Current session only: logoutAll=false | |
|---|---|---|
| Sessions | Deletes all sessions of the user across all applications of the organization | Deletes the current session |
| Access tokens | Expires all access tokens issued to the user | Expires the tokens that were issued in the current session |
| Notification | Contains all session IDs and the hashes of all tokens of the user | Contains the current session ID and the hashes of all tokens of the user |
当用户在一台设备或浏览器上登出,而在其他设备上保持登录状态时,使用 logoutAll=false。
此端点与 RP 发起的注销不同,后者是标准 OIDC 结束会话端点,由单个客户端为其自身会话调用。
调用 SSO 注销端点
GET or POST /api/sso-logout?logoutAll=<true|false>
| Parameter | Required | Description |
|---|---|---|
logoutAll | No | true, 1, or omitted: sign out of all sessions. Any other value, such as false or 0: sign out of the current session only |
以用户身份对请求进行身份验证,可在 Authorization 标头中携带访问令牌,或使用会话 Cookie。参见选择身份验证方法。
注销所有会话:
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"
使用会话 Cookie 进行身份验证:
curl -X POST https://door.casdoor.com/api/sso-logout \
--cookie "casdoor_session_id=abc123def456"
成功的请求将返回:
{
"status": "ok",
"msg": "",
"data": ""
}
| Field | Description |
|---|---|
status | "ok" on success, "error" on failure |
msg | Error message on failure, otherwise empty |
data | Empty 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
无论请求结果如何,随后都应清除应用的本地状态:存储的令牌、缓存的用户信息以及本地会话 Cookie。即使用户向 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 会向用户注册所用的每个应用的通知提供商发送通知。您的应用利用该通知来结束该用户的自身会话。
配置通知提供商
-
在 Casdoor 管理控制台中,添加一个通知提供商,例如类型为 Custom HTTP,并将其添加到应用中。
-
对于 Custom HTTP 提供商,请设置以下字段:
Field Value Endpoint Endpoint of your application that receives the notification, for example https://app.example.com/api/logout-webhookMethod POSTParameter content. 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"
}
| Field | Description |
|---|---|
sessionIds | IDs of the sessions that were ended |
accessTokenHashes | 用户在两种模式下的访问令牌的 SHA-256 哈希值,包括已过期的令牌。当 logoutAll=false 时,列表中还包含其他会话的令牌(这些令牌仍然有效),因此请先匹配 sessionIds。将此处的哈希值与您应用持有的令牌哈希值进行比较,以找到需要结束的会话 |
nonce | Random value that protects against replay |
timestamp | Unix time at which Casdoor created the notification |
signature | HMAC-SHA256 signature, computed with the client secret of the application |
验证通知
任何能够访问您端点的人都可以向其发送请求。在处理通知之前:
-
验证签名。在 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;
} -
拒绝过旧的通知,例如超过五分钟的通知:
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);
} -
结束您的应用中与
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 服务提供商发起 单点登出。仅通知使用该会话登录的应用。
- 用户被管理员或同步器禁止或删除。
- 在 Casdoor 管理控制台中,打开应用的编辑页面。
- 将 Backchannel logout URL (
backchannelLogoutUri) 设置为您的应用中接收注销令牌的端点。
Casdoor 向该 URI 发送带有 logout_token 参数的 HTTP POST 请求。该令牌是一个 JSON Web Token (JWT),包含 iss、sub、aud、iat、exp 和 jti 声明以及 http://schemas.openid.net/event/backchannel-logout 事件。令牌在签发后 2 分钟过期。仅在 SSO 登出端点、会话限制和 SAML 单点登出的情况下,令牌才携带包含 Casdoor 会话 ID 的 sid 声明。为 /api/logout 以及为被禁止或被删除的用户发送的令牌没有 sid,因此会结束 sub 中指定用户的所有会话。Casdoor 会跳过那些没有后端通道登出 URL 的应用。
注销 SAML 应用
对于通过 SAML 登录用户的应用,当用户使用 /api/sso-logout 的两种模式或 /api/logout 注销时,Casdoor 会向应用的 SAML single logout URL 发送签名的 SAML LogoutRequest。SAML 服务提供商也可以在 Casdoor 处发起注销。参见单点注销。
故障排除
用户仍登录在某些应用中
- 检查所有应用是否都通过 Casdoor 登录用户,并属于同一组织。
- 检查每个应用是否在每次请求时验证令牌,或响应注销通知。仅依赖其自身本地会话的应用不会注意到注销操作。
注销后令牌仍然有效
- 检查请求是否发送至
/api/sso-logout,并已作为用户完成身份验证。 - 检查您的应用是否未缓存令牌验证的结果。
注销后,令牌记录仍保留在数据库中,其 ExpiresIn 设置为 0。令牌检查端点和刷新令牌端点会拒绝这些令牌。使用此类刷新令牌的客户端会收到错误 invalid_grant,消息为 "refresh token is expired"。如果 Casdoor 不知道某个刷新令牌(例如被刷新令牌轮换替换掉的令牌),则会失败并显示 "refresh token is invalid or revoked"。
端点返回错误
| Status | Cause | What to do |
|---|---|---|
| HTTP 401 | The access token is invalid or expired | Clear the local state and send the user to the sign-in page |
| HTTP 403 | The user isn't allowed to sign out. This points to a configuration problem | Check the configuration of the application |
| HTTP 500 | Error on the server | Log 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();
}
}