认证
本篇搭建一套完整的账号登录与权限保护接口,涵盖签发与注销 Bearer 令牌、/login 防爆破限流、角色权限检查以及修改密码前的二次密码确认。
flowchart LR
req["携带 Bearer 令牌的请求"] --> auth["AuthPlugin 识别当前用户"]
auth --> role["GuardAccess 加载角色与权限"]
role --> route_guard["路由组或 Procedure 角色检查"]
role --> row_policy["单条记录 Policy 权限检查"]配置登录保护范围与接口限流#
首先开启登录认证与安全限流两个 feature,新建 Cargo.toml:
[package]
name = "guide-auth"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["auth", "security"] }挂载 AuthPlugin 后,auth.default_policy 默认值是 required(除了标了 public 的 Procedure 和列入 anonymous_paths 的路径外,所有请求都必须登录)。这里为了演示按路径前缀指定保护范围,设为默认允许匿名访问,只要求 /me 开头的接口必须登录。新建 config/auth.toml:
default_policy = "anonymous"
required_paths = ["/me"]接着用 SecurityPlugin 给 /login 接口加上按客户端来源限流(每分钟最多 5 次,超出直接返回 429,每条规则可在 requests_per_second、requests_per_minute、requests_per_hour 中任选其一)。新建 config/security.toml:
[[rate_limit.routes]]
path_prefix = "/login"
requests_per_minute = 5
burst = 5编写登录、登出与二次密码确认#
下面的 src/auth.rs 包含生产环境账号系统的三道核心防线:
- 密码脱敏与防猜测用户名(
login/logout):用SecretString接收密码,打印日志或报错时会自动替换成<redacted>。当输入的用户名不存在时,依然把None传给verify_and_upgrade做一次同等耗时的 Argon2id 哈希运算,再与密码错误统一返回401invalid_credentials,防止外部通过响应时间快慢猜出系统里有哪些账号。 - 加载角色与权限(
Roles/reports):实现GuardAccess为 1 号用户alice赋予admin角色和report.view权限;未登录访问返回401unauthorized(若底层会话存储故障则返回503authentication_unavailable,避免前端因网络抖动误踢用户下线)。 - 改密前二次密码确认(
confirm_password/change_password):用户挂着登录态离开电脑时,直接允许改密存在风险。调用ctx.recent_auth()?.confirm(..)验证一次当前密码后签发短期确认令牌,客户端将其放入x-password-confirmation请求头才能通过/me/password的检查。
新建 src/auth.rs:
use kxed::access::{AccessError, GuardAccess};
use kxed::config::SecretString;
use kxed::identity::Identity;
use kxed::plugins::auth::{AuthError, AuthPrincipal, AuthSessionValidator, LoginOptions, StoredAuthSession};
use kxed::prelude::*;
struct Account {
id: &'static str,
name: &'static str,
password_hash: &'static str,
}
const PASSWORD_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$mJfhhg2fcfZQEdxdBPkEWg$KVeOODDsOGTKIEa8avz/Q0fvdUhm+Yc5+gHIYc1ZpRw";
const ACCOUNTS: [Account; 2] = [
Account { id: "1", name: "alice", password_hash: PASSWORD_HASH },
Account { id: "2", name: "bob", password_hash: PASSWORD_HASH },
];
pub(crate) struct Accounts;
impl AuthSessionValidator for Accounts {
async fn is_valid(&self, session: &StoredAuthSession) -> Result<bool, AuthError> {
Ok(ACCOUNTS.iter().any(|account| account.id == session.principal.subject))
}
}
#[derive(Deserialize)]
pub(crate) struct Login {
name: String,
password: SecretString,
}
pub(crate) async fn login(ctx: AppCtx, Json(login): Json<Login>) -> Result<String, AppErr> {
let account = ACCOUNTS.iter().find(|account| account.name == login.name);
let hash = account.map(|account| account.password_hash.to_owned());
let check = ctx.password_verifier()?.verify_and_upgrade(login.password, hash).await?;
let Some(account) = account.filter(|_| check.is_valid()) else {
return Err(rejected());
};
let issued = ctx.auth_sessions()?.issue_token(AuthPrincipal::new(account.id), LoginOptions::default()).await?;
Ok(issued.token.expose_secret().to_owned())
}
pub(crate) struct Roles;
impl GuardAccess for Roles {
async fn grants(&self, identity: &Identity) -> Result<Grants, AccessError> {
let admin = identity.subject() == "1";
Ok(Grants::new(admin.then_some("admin"), ["report.view"])?)
}
}
pub(crate) async fn reports(ctx: AppCtx) -> Result<String, AppErr> {
let grants = ctx.grants().await?;
grants.require_role("admin")?;
grants.require_permission("report.view")?;
Ok("reports\n".to_owned())
}
pub(crate) async fn me(ctx: AppCtx) -> Result<String, AppErr> {
let identity = ctx.require_identity().await?;
Ok(format!("{}\n", identity.subject()))
}
pub(crate) async fn logout(ctx: AppCtx) -> Result<StatusCode, AppErr> {
let identity = ctx.require_identity().await?;
ctx.auth_sessions()?.revoke_current(&identity).await?;
Ok(StatusCode::NO_CONTENT)
}
fn rejected() -> AppErr {
AppErr::new(StatusCode::UNAUTHORIZED, "invalid credentials").with_code("invalid_credentials")
}
#[derive(Deserialize)]
pub(crate) struct Password {
password: SecretString,
}
pub(crate) async fn confirm_password(ctx: AppCtx, Json(form): Json<Password>) -> Result<String, AppErr> {
let identity = ctx.require_identity().await?;
let account = ACCOUNTS.iter().find(|account| account.id == identity.subject()).ok_or_else(AppErr::unauthorized)?;
ctx.recent_auth()?.confirm(&identity, form.password, account.password_hash.to_owned()).await
}
pub(crate) async fn change_password(ctx: AppCtx, Json(form): Json<Password>) -> Result<StatusCode, AppErr> {
let _new_hash = ctx.password_verifier()?.hash(form.password).await?;
Ok(StatusCode::NO_CONTENT)
}最后在入口注册 SecurityPlugin 与 AuthPlugin,并给 PUT /me/password 挂上 require_recent_auth(要求 15 分钟内刚确认过当前密码)。新建 src/main.rs:
mod auth;
use kxed::plugins::auth::{require_recent_auth, AuthPlugin, MemoryAuthStore};
use kxed::plugins::security::SecurityPlugin;
use kxed::prelude::*;
use std::time::Duration;
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(SecurityPlugin::new())
.plugin(
AuthPlugin::new()
.with_store(MemoryAuthStore::new(1024)?, auth::Accounts)
.with_access(auth::Roles),
)
.routes(|router| {
router
.route("/login", post(auth::login))
.route("/me", get(auth::me))
.route("/me/logout", post(auth::logout))
.route("/me/reports", get(auth::reports))
.route("/me/confirm-password", post(auth::confirm_password))
.route(
"/me/password",
put(auth::change_password).layer(require_recent_auth(Duration::from_secs(900))),
);
})
.run()
.await
}验证#
二次密码确认令牌需要使用应用主密钥 app.key 签名,先生成随机密钥写入 config/app.toml,然后启动服务:
printf 'key = "%s"\n' "$(openssl rand 64 | base64 | tr -d '\n')" > config/app.tomlcargo run另开一个终端依次验证登录注销、角色拦截与二次密码确认:
curl --silent --output /dev/null --write-out '%{http_code}\n' http://127.0.0.1:8080/me
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"name":"alice","password":"wrong"}' http://127.0.0.1:8080/login
TOKEN=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/login)
curl --fail -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me
curl --silent --output /dev/null --write-out '%{http_code}\n' -X POST -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me/logout
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $TOKEN" http://127.0.0.1:8080/me
BOB=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"bob","password":"correct horse battery"}' http://127.0.0.1:8080/login)
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $BOB" http://127.0.0.1:8080/me/reports
ALICE=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/login)
curl --fail -H "authorization: Bearer $ALICE" http://127.0.0.1:8080/me/reports
curl --silent --output /dev/null --write-out '%{http_code}\n' -X PUT -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"password":"a new horse battery"}' http://127.0.0.1:8080/me/password
CONFIRM=$(curl --fail --silent -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"password":"correct horse battery"}' http://127.0.0.1:8080/me/confirm-password)
curl --silent --output /dev/null --write-out '%{http_code}\n' -X PUT -H "authorization: Bearer $ALICE" -H "x-password-confirmation: $CONFIRM" -H 'content-type: application/json' -d '{"password":"a new horse battery"}' http://127.0.0.1:8080/me/password预期输出:
401
401
1
204
401
403
reports
403
204核对这 9 行输出:
- 前 5 行(登录与立即注销):未带令牌访问
/me和输错密码都返回401;正确登录后拿到用户 ID1;调用logout返回204后,同一个令牌再次请求立即变成401。 - 后 4 行(角色检查与二次确认):没有
admin角色的bob访问报表返回403,alice成功读到reports;不带确认头直接改密被拦下返回403,先调confirm-password把确认凭据放进请求头后改密返回204。
内建账户 JSON 路由与存储#
如果不想自己建用户表和手写登录逻辑,配合 SeaOrmPlugin 直接使用 AuthPlugin::new().with_accounts() 并挂载 AccountApiPlugin::new("/api/auth"),就能一键获得 /login、/login/two-factor、/logout、/confirm-password、/totp 和 /totp/confirm 标准接口(链式加 .with_registration() 开启注册接口,加 .with_issuer("Books API") 设置手机验证器显示名,详见 账户 JSON 路由;需要定制路径见 账户注册与登录接口)。
注意 MemoryAuthStore 只保存在单实例内存里,重启就会清空。正式上线或部署多实例集群时,请按下表选择合适的账户与会话接入方式(用户主键也会自动写入数据表的审计列,建议统一使用 "1" 这类整数文本,详见 认证合同):
| 接入方式 | 适用场景 | 提供的能力 |
|---|---|---|
AuthPlugin::new().with_store(MemoryAuthStore::new(1024)?, validator) | 本地教程演示与单测 | 纯内存保存令牌会话,零外部依赖,实例重启即清空 |
AuthPlugin::new().with_database(validator) | 已有自建用户表、需多实例共享会话 | 会话存入业务关系数据库,账户有效性由你的 validator 核验 |
AuthPlugin::new().with_accounts() + AccountApiPlugin | 新项目开箱即用账户体系 | 自动创建 kxed_users 表并提供注册、登录、TOTP 两步验证与 auth user 运维命令 |
确认密码与两步验证设置#
- 哈希生成与平滑升级:注册和改密时调用
ctx.password_verifier()?.hash(form.password).await?生成 Argon2id 哈希(配置项为auth.password.hash_*;Cookie 会话登录可在LoginOptions里传remember开启auth.stateful.remember_lifetime)。日后调高哈希强度参数时,旧用户登录会返回PasswordCheck::Rehashed(new_hash),顺手写回用户表即可无感升级(见 auth README 的登录时升级哈希)。 - 二次密码确认:未带有效确认头时返回
403auth_password_confirmation_required;确认密码输错返回422invalid_password,300 秒内连续输错 5 次返回429(见 确认密码)。 - TOTP 两步验证:通过
TotpSetup的begin、confirm、disable和regenerate_recovery_codes即可接入手机验证器 App(自定义账户表只需实现TotpAccounts,见 JSON 应用的 TOTP 管理)。
生成两步验证绑定二维码密钥的第一步写法如下:
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, "Books API", &user.username).await?))
}角色与权限#
角色和权限列表由 AuthPlugin::with_access 注册(如果漏注册,所有权限检查都会返回 403 并在日志提示 guard has no GuardAccess source)。权限字符串支持 * 全通配和 report.* 前缀通配(见 认证合同的角色与权限);如果要签发只允许调少数接口的受限个人访问令牌,在 LoginOptions 里只填部分 abilities 即可(见 AUTH 签发与使用)。
日常业务写成 Procedure 时直接在函数宏上声明即可,与原生 HTTP 路由的对应关系如下:
| 权限控制需求 | Procedure 宏写法 | 原生 HTTP 路由写法 | 未通过时返回 |
|---|---|---|---|
| 放行未登录匿名请求 | #[query(public, ..)] | 加入 auth.anonymous_paths | 正常放行 |
| 要求已登录(任意账号) | 默认行为(不标 public) | ctx.require_identity().await? | 401 unauthorized |
| 要求具备指定角色之一 | role = "admin" 或 role = ["admin", "ops"] | .layer(require_role("admin")) | 403 forbidden |
| 要求具备指定权限 | permission = "report.view"(写多个表示全部满足) | .layer(require_permission("report.view")) | 403 forbidden |
| 检查能否操作某条记录 | 参数用 Found<E> 并标 can = "update" | 查出数据后调 ctx.authorize("update", &row).await? | 403 或 404 |
| 敏感操作二次密码确认 | recent_auth = "15m" | .layer(require_recent_auth(..)) | 403 auth_password_confirmation_required |
WebSocket 长连接内可用 socket.require_role("admin").await? 检查角色并用 socket.revalidate_every(..) 定期重验令牌是否被撤销(见 Ws 的方法 与 撤销与活动);想把所有 URL 与 HTTP 方法的角色表集中写在一处管理时,开启 authz feature 并挂载 AuthorizationPlugin::new()(见 authz README)。
对象级授权#
角色只能判断「他是不是编辑」,而判断「他是不是这篇文章的作者、能不能改这一行数据」需要拿到具体记录再做决定。为数据模型实现 Policy<T> 并在 App::policy 注册即可(用 gate_before 还能统一给超级管理员一票放行):
use kxed::identity::Identity;
use kxed::prelude::*;
struct PostPolicy;
impl Policy<Post> for PostPolicy {
async fn check(&self, who: &Identity, grants: &Grants, action: &str, post: &Post) -> Decision {
match action {
"view" => Decision::Allow,
"update" => (grants.has_permission("posts.update") && post.author_id == who.subject()).into(),
_ => Decision::Deny,
}
}
}
async fn update(ctx: AppCtx, Path(id): Path<u64>) -> Result<&'static str, AppErr> {
let post = find_post(&ctx, id).await?;
ctx.authorize("update", &post).await?;
Ok("updated")
}
App::new()
.policy::<Post>(PostPolicy)
.gate_before(|_, grants| grants.has_role("super-admin").then_some(Decision::Allow));- 裁决响应与界面判断:
Decision::Deny返回403,Decision::NotFound返回404(用于隐藏私有记录是否存在);只拿布尔值决定按钮显隐时调ctx.can("update", &post).await?(漏注册App::policy时返回500policy_not_registered,见 认证合同的对象级授权)。 - 在后台任务里鉴权:操作需要丢给
#[task]异步运行时,在请求里调who.for_task()把身份打包进任务参数,执行任务时调ctx.authorize_as(&self.who, "update", &post).await?即可(见 SPEC 执行位置)。
常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
角色检查对所有已登录用户都返回 403 | AuthPlugin 未调用 .with_access(..) 挂载角色数据源,或签发令牌时限制了 abilities 子集 | 补挂 .with_access(Roles),全权限登录使用 LoginOptions::default() |
二次密码确认或两步验证返回 500 app_key_missing | 未配置应用主密钥 app.key | 用 openssl rand 64 | base64 | tr -d '\n' 生成密钥写入 config/app.toml 或 KXED__APP__KEY |
调 ctx.authorize 返回 500 policy_not_registered | 忘了在 App::new() 上注册该数据类型的 Policy | 补上 .policy::<Post>(PostPolicy),校验时传 &Post 引用 |
挂在反向代理后全员登录触发 429 rate_limited | 未配置可信代理策略,所有请求共用代理节点 IP 计入防刷配额 | 在 config/security.toml 配置 trusted_proxy.policy = "forwarded_headers" 与代理网段 |
参考#
- 签名 URL、加密与 webhook:
app.key主密钥、限时签名链接、加密 Cookie 与 Webhook 验签 AUTH.md:Cookie 会话、令牌存储边界、认证事件 与 模拟登录- auth README 的未登录跳转 与 JSON 两步登录
- 审计字段 与 fly-tenant 示例