客人身份验证
访客身份验证会创建无用户名或密码的临时用户。 用户可立即使用该应用;如有需要,稍后可进行完整注册。
先决条件
在使用访客身份验证之前,请确保已在应用程序中启用以下设置:
- 启用注册 — 客户端用户创建需要允许注册。
- 启用访客登录 — 明确启用允许
guest-user代码流的开关。 若未启用,令牌端点将返回invalid_grant。
这两个设置均位于应用程序编辑页面的身份验证选项卡下。 访客身份验证不适用于内置组织。
创建客人用户
使用特殊代码guest-user向令牌端点发送POST请求:
POST https://<CASDOOR_HOST>/api/login/oauth/access_token
请求正文:
{
"grant_type": "authorization_code",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"code": "guest-user"
}
备注
代码“guest-user”是Casdoor的一项扩展功能,用于创建一个访客用户,而非完成正常的OAuth代码流程。
响应:
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
Casdoor创建了一个用户,用户名为guest_<0>,随机密码,并标记为guest-user。
升级为普通用户
当用户通过用户更新 API 设置或更改其用户名(更改为不以“guest_”开头的名称)或设置密码时,他们将被升级:标签变为“normal-user”,并可使用常规登录方式。
限制
访客用户无法通过正常登录页面登录,直至他们完成升级(设置真实用户名或密码)。
示例集成
// Create a guest user
async function createGuestUser() {
const response = await fetch('https://your-casdoor-host/api/login/oauth/access_token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'authorization_code',
client_id: 'your_client_id',
client_secret: 'your_client_secret',
code: 'guest-user'
})
});
const data = await response.json();
return data.access_token;
}
// Later, upgrade the guest user
async function upgradeGuestUser(accessToken, newUsername, newPassword) {
const response = await fetch('https://your-casdoor-host/api/update-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
name: newUsername,
password: newPassword
})
});
return response.json();
}