账户注册与登录接口
本篇基于内建 SeaORM 账户表实现注册、登录、两步验证与二次密码确认销户接口。需要定制路由路径或返回结构时直接调用 ctx.accounts() 组装,无需手写密码哈希与防刷逻辑。
配置数据库、认证与限流#
第 1 步,新建 Cargo.toml,启用认证、SQLite 与安全限流特性:
[package]
name = "guide-accounts"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["auth", "seaorm-sqlite", "security"] }第 2 步,新建 config/database.toml,指向本地 SQLite 文件(将 accounts.sqlite* 加入 .gitignore):
url = "sqlite://accounts.sqlite?mode=rwc"第 3 步,新建 config/auth.toml,仅对 /me 与 /logout 强制校验登录态,放行注册与登录入口:
default_policy = "anonymous"
required_paths = ["/me", "/logout"]第 4 步,新建 config/security.toml,为 /login 与 /register 配置按客户端来源限流(按最长前缀匹配,/login/two-factor 自动共用 /login 配额):
[[rate_limit.routes]]
path_prefix = "/login"
requests_per_minute = 5
burst = 5
[[rate_limit.routes]]
path_prefix = "/register"
requests_per_minute = 5
burst = 5编写账户接口与入口#
第 5 步,新建 src/accounts.rs,封装注册、登录、两步验证、改密、TOTP 绑定、登出与注销账号:
use kxed::config::SecretString;
use kxed::plugins::auth::{AuthPrincipal, LoginOptions, LoginStep, TotpEnrollment};
use kxed::prelude::*;
use kxed::serde_json::{json, Value};
#[derive(Deserialize)]
pub(crate) struct Credentials {
username: String,
password: SecretString,
}
#[derive(Deserialize)]
pub(crate) struct TwoFactor {
challenge: String,
code: String,
}
#[derive(Deserialize)]
pub(crate) struct Password {
password: SecretString,
}
#[derive(Deserialize)]
pub(crate) struct EnableTotp {
setup: String,
code: String,
}
async fn issue(ctx: &AppCtx, principal: AuthPrincipal) -> Result<Json<Value>, AppErr> {
let issued = ctx.auth_sessions()?.issue_token(principal, LoginOptions::default()).await?;
Ok(Json(json!({ "token": issued.token.expose_secret() })))
}
pub(crate) async fn register(ctx: AppCtx, Json(form): Json<Credentials>) -> Result<Json<Value>, AppErr> {
let principal = ctx.accounts()?.register(&form.username, form.password).await?;
issue(&ctx, principal).await
}
pub(crate) async fn login(ctx: AppCtx, Json(form): Json<Credentials>) -> Result<Json<Value>, AppErr> {
match ctx.accounts()?.login(&form.username, form.password).await? {
LoginStep::Authenticated(principal) => issue(&ctx, principal).await,
LoginStep::Challenge(challenge) => Ok(Json(json!({ "two_factor": challenge }))),
}
}
pub(crate) async fn two_factor(ctx: AppCtx, Json(form): Json<TwoFactor>) -> Result<Json<Value>, AppErr> {
let principal = ctx.accounts()?.verify(&form.challenge, &form.code).await?;
issue(&ctx, principal).await
}
pub(crate) async fn me(ctx: AppCtx) -> Result<Json<Value>, AppErr> {
let user = ctx.accounts()?.current(&ctx.require_identity().await?).await?;
Ok(Json(json!({ "id": user.id, "username": user.username, "two_factor": user.totp_secret.is_some() })))
}
pub(crate) async fn confirm_password(ctx: AppCtx, Json(form): Json<Password>) -> Result<Json<Value>, AppErr> {
let identity = ctx.require_identity().await?;
let confirmation = ctx.accounts()?.confirm_password(&identity, form.password).await?;
Ok(Json(json!({ "confirmation": confirmation })))
}
pub(crate) async fn change_password(ctx: AppCtx, Json(form): Json<Password>) -> Result<Json<Value>, AppErr> {
let principal = ctx.accounts()?.change_password(&ctx.require_identity().await?, form.password).await?;
issue(&ctx, principal).await
}
pub(crate) async fn begin_totp(ctx: AppCtx) -> Result<Json<TotpEnrollment>, AppErr> {
let identity = ctx.require_identity().await?;
let accounts = ctx.accounts()?;
let user = accounts.current(&identity).await?;
Ok(Json(accounts.totp_setup().begin(&identity, "Accounts Demo", &user.username).await?))
}
pub(crate) async fn confirm_totp(ctx: AppCtx, Json(form): Json<EnableTotp>) -> Result<Json<Vec<String>>, AppErr> {
let identity = ctx.require_identity().await?;
let codes = ctx.accounts()?.totp_setup().confirm(&identity, &form.setup, &form.code).await?;
Ok(Json(codes))
}
pub(crate) async fn recovery_codes(ctx: AppCtx) -> Result<Json<Vec<String>>, AppErr> {
let identity = ctx.require_identity().await?;
Ok(Json(ctx.accounts()?.totp_setup().regenerate_recovery_codes(&identity).await?))
}
pub(crate) async fn disable_totp(ctx: AppCtx) -> Result<(), AppErr> {
let identity = ctx.require_identity().await?;
ctx.accounts()?.totp_setup().disable(&identity).await
}
pub(crate) async fn logout(ctx: AppCtx) -> Result<(), AppErr> {
let identity = ctx.require_identity().await?;
ctx.auth_sessions()?.revoke_current(&identity).await?;
Ok(())
}
pub(crate) async fn delete_me(ctx: AppCtx) -> Result<StatusCode, AppErr> {
ctx.accounts()?.delete_current(&ctx.require_identity().await?).await?;
Ok(StatusCode::NO_CONTENT)
}第 6 步,注册 SecurityPlugin、SeaOrmPlugin 与 AuthPlugin::new().with_accounts(),并为改密、销户与 TOTP 路由挂上 15 分钟二次密码确认中间件,写 src/main.rs:
mod accounts;
use kxed::plugins::auth::{require_recent_auth, AuthPlugin};
use kxed::plugins::seaorm::SeaOrmPlugin;
use kxed::plugins::security::SecurityPlugin;
use kxed::prelude::*;
use std::time::Duration;
#[kxed::main]
async fn main() -> kxed::Result<()> {
let confirmed = require_recent_auth(Duration::from_secs(900));
App::new()
.plugin(SecurityPlugin::new())
.plugin(SeaOrmPlugin::new())
.plugin(AuthPlugin::new().with_accounts())
.routes(move |router| {
router
.route("/register", post(accounts::register))
.route("/login", post(accounts::login))
.route("/login/two-factor", post(accounts::two_factor))
.route("/logout", post(accounts::logout))
.route("/me", get(accounts::me))
.route("/me", delete(accounts::delete_me).layer(confirmed))
.route("/me/confirm-password", post(accounts::confirm_password))
.route("/me/password", put(accounts::change_password).layer(confirmed))
.route(
"/me/two-factor",
post(accounts::begin_totp).delete(accounts::disable_totp).layer(confirmed),
)
.route("/me/two-factor/confirm", post(accounts::confirm_totp).layer(confirmed))
.route("/me/two-factor/recovery-codes", post(accounts::recovery_codes).layer(confirmed));
})
.run()
.await
}验证#
生成 64 字节应用主密钥写入 config/app.toml(供二次密码确认令牌与两步验证密钥加密使用),再启动服务:
printf 'key = "%s"\n' "$(openssl rand 64 | base64 | tr -d '\n')" > config/app.tomlcargo run依次验证注册、大小写不敏感判重、弱密码拦截、错密拦截、登录后读 /me、登出失效,以及携带确认头销户:
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"username":"Alice","password":"correct horse battery"}' http://127.0.0.1:8080/register
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"username":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/register
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"username":"bob","password":"short"}' http://127.0.0.1:8080/register
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"username":"alice","password":"wrong horse battery"}' http://127.0.0.1:8080/login
TOKEN=$(curl --fail --silent -H 'content-type: application/json' -d '{"username":"ALICE","password":"correct horse battery"}' http://127.0.0.1:8080/login | grep -o '"token":"[^"]*"' | cut -d '"' -f 4)
curl --fail --silent -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me | grep -o '"username":"[^"]*"'
curl --silent --output /dev/null --write-out '%{http_code}\n' -X POST -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/logout
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me
TOKEN=$(curl --fail --silent -H 'content-type: application/json' -d '{"username":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/login | grep -o '"token":"[^"]*"' | cut -d '"' -f 4)
CONFIRMED=$(curl --fail --silent -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' -d '{"password":"correct horse battery"}' http://127.0.0.1:8080/me/confirm-password | grep -o '"confirmation":"[^"]*"' | cut -d '"' -f 4)
curl --silent --output /dev/null --write-out '%{http_code}\n' -X DELETE -H "authorization: Bearer $TOKEN" -H "x-password-confirmation: $CONFIRMED" http://127.0.0.1:8080/me
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me预期输出:
200
409
422
401
"username":"alice"
200
401
204
401- 前 5 行对应注册成功
200、重名冲突409、密码过短422、密码错误401与归一化为小写的"username":"alice"。 - 后 4 行对应登出返回
200且旧 token 立即返401,重新登录并携带x-password-confirmation销户返回204后原 token 同步作废。
自动建表、级联销户与运维命令#
- 自动建表与会话共享:
AuthPlugin::new().with_accounts()启动时自动创建kxed_users、会话与恢复码表,多实例只要连同一个关系数据库并共用app.key即可共享登录态与二次确认凭据。 - 改密作废旧令牌:调用
change_password或停用账号后,该用户的全部存量令牌立即失效,返回的新令牌只代表本次重新认证的会话。 - 外键约束下的销户:当业务表仍用外键引用当前用户时,
delete_current会返回409account_referenced;改为在ctx.db()?.begin_write().await?事务内先清理或转移业务行,再调ctx.accounts()?.delete_current_within(&txn, &identity).await?。 - 内置账号运维命令:挂载
with_accounts()后二进制自动获得auth user create/show/list/password/disable/delete与auth totp reset/rekey(完整命令表见 运维命令)。
常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
访问 /me/confirm-password 或开启 TOTP 返回 500 app_key_missing | 未配置应用主密钥 app.key | 用 openssl rand 64 | base64 | tr -d '\n' 生成密钥写入 config/app.toml 或 KXED__APP__KEY |
注销账户 delete_current 返回 409 account_referenced | 业务表存在指向该用户 ID 的外键记录 | 在 begin_write 事务内先删除或移交业务记录,再调 delete_current_within(&txn, &identity) |
重复注册同名大写账号返回 409 | 内建账户表按小写归一化用户名做唯一索引 | 属于防大小写撞名保护;提示用户换名或直接登录 |
多实例下确认密码头偶发返回 403 | 不同实例配置的 app.key 不一致 | 确保集群全部实例使用同一把 KXED__APP__KEY |
参考#
- 认证:
AuthPlugin守卫、角色权限检查、Policy对象级授权与AccountApiPlugin - auth README 的 SeaORM 账户表:登录防爆破配额、账户表结构与两步验证接口
- 迁移:在
Seeder中幂等初始化默认管理员账户