pub struct SaTokenConfig {Show 48 fields
pub token_name: String,
pub timeout: i64,
pub active_timeout: i64,
pub dynamic_active_timeout: bool,
pub auto_renew: bool,
pub renew_threshold: i64,
pub is_concurrent: bool,
pub is_share: bool,
pub token_style: TokenStyle,
pub is_log: bool,
pub is_read_cookie: bool,
pub is_read_header: bool,
pub is_read_body: bool,
pub token_prefix: Option<String>,
pub cookie: TokenCookieConfig,
pub jwt_secret_key: Option<String>,
pub jwt_algorithm: Option<String>,
pub jwt_issuer: Option<String>,
pub jwt_audience: Option<String>,
pub jwt_fallback_on_error: bool,
pub enable_nonce: bool,
pub nonce_timeout: i64,
pub enable_refresh_token: bool,
pub refresh_token_timeout: i64,
pub storage_key_prefix: String,
pub key_layout: SaKeyLayout,
pub max_login_count: i64,
pub overflow_logout_mode: LogoutMode,
pub replaced_login_exit_mode: ReplacedLoginExitMode,
pub replaced_range: ReplacedRange,
pub right_now_create_token_session: bool,
pub token_session_check_login: bool,
pub logout_range: LogoutRange,
pub is_logout_keep_token_session: bool,
pub grant_cache_ttl: i64,
pub grant_cache_max_entries: usize,
pub grant_cache_single_flight: bool,
pub grant_request_scope: bool,
pub grant_write_policy: GrantWritePolicy,
pub role_wildcard: bool,
pub context_auto_create: bool,
pub http_basic: String,
pub same_token_timeout: i64,
pub same_token_header: String,
pub max_try_times: i32,
pub sign_secret_key: Option<String>,
pub sign_window_secs: i64,
pub serializer: SharedSerializer,
}Expand description
sa-token 全局配置。 Global sa-token configuration.
Fields§
§token_name: StringToken 名称(header / cookie / body 中的键名) Token name (key used in header, cookie, or body)
timeout: i64Token 有效期(秒),-1 表示永久有效
Token lifetime in seconds; -1 means never expires
active_timeout: i64Token 最低活跃频率(秒),-1 表示不限制。
超过该间隔未活跃则冻结(TokenInactive);开启 auto_renew 时亦用于续签时长。
Minimum activity interval in seconds; -1 disables the check.
Idle longer than this freezes the token (TokenInactive); also used as
the renewal window when auto_renew is enabled.
dynamic_active_timeout: boolPer-token activity window override. 是否启用逐 token 的活跃窗口覆盖。
auto_renew: bool是否开启自动续签(0.2.0 起默认 false,避免每次读 token 都写存储)
Whether to enable auto-renewal (defaults to false since 0.2.0 to avoid
a storage write on every token read)
renew_threshold: i64续签阈值(秒):仅当 token 剩余有效时间低于该值时才真正触发续签写入。
语义(三段):
< 0(如-1):不启用阈值,每次读取都续签 —— 兼容 0.1.x 旧行为== 0:仅当剩余时间<= 0(已到期边界)才续签> 0:剩余时间<=阈值时才续签(推荐,默认300)
注意:本字段仅在 auto_renew == true 时生效。
Renewal threshold in seconds: a renewal write happens only when the token’s remaining lifetime drops below this value.
< 0: threshold disabled, renew on every read (0.1.x behaviour)== 0: renew only when remaining lifetime<= 0> 0: renew when remaining lifetime<=threshold (recommended; default300)
Only effective when auto_renew == true.
is_concurrent: bool是否允许同一账号并发登录 Whether the same account may log in concurrently
Concurrent logins share one token when true (default false).
为 true 时同一账号并发登录共用一个 token(默认 false)。
token_style: TokenStyleToken 风格(uuid、simple-uuid、random-32、random-64、random-128 等) Token generation style (uuid, simple-uuid, random-32/64/128, etc.)
is_log: bool是否输出操作日志 Whether to emit operation logs
是否从 cookie 中读取 token Whether to read the token from cookies
is_read_header: bool是否从 header 中读取 token Whether to read the token from headers
is_read_body: bool是否从请求体中读取 token Whether to read the token from the request body
token_prefix: Option<String>Optional token prefix. None = still strip a leading Bearer .
可选 token 前缀。None 时仍剥离开头的 Bearer 。
Cookie write settings (opt-in). Cookie 下发配置(默认不写)。
jwt_secret_key: Option<String>JWT 密钥(使用 JWT 风格时) JWT secret key (when using the JWT token style)
jwt_algorithm: Option<String>JWT 算法(默认 HS256)
JWT algorithm (default HS256)
jwt_issuer: Option<String>JWT 签发者(iss)
JWT issuer (iss)
jwt_audience: Option<String>JWT 受众(aud)
JWT audience (aud)
jwt_fallback_on_error: boolJWT 生成失败时是否回退为 UUID(默认 false);失败时始终记录日志
Whether to fall back to UUID when JWT generation fails (default false); always log on failure
enable_nonce: bool是否启用防重放攻击(nonce 机制) Whether to enable anti-replay protection via nonce
nonce_timeout: i64Nonce 有效期(秒),-1 表示沿用 token timeout
Nonce lifetime in seconds; -1 follows token timeout
enable_refresh_token: bool是否启用 Refresh Token Whether to enable refresh tokens
refresh_token_timeout: i64Refresh Token 有效期(秒),默认 7 天(604800)
Refresh-token lifetime in seconds (default 7 days / 604800)
storage_key_prefix: String存储键前缀(Redis / 数据库等后端的键命名)。
默认 "sa:",所有逻辑键以此为前缀,如 "sa:token:"、"sa:session:"。
Storage key prefix for Redis/DB backends.
Default "sa:"; all logical keys are prefixed, e.g. "sa:token:", "sa:session:".
key_layout: SaKeyLayout存储键布局策略(A3-1) Storage key layout strategy (A3-1)
max_login_count: i64同一账号最大登录数量,-1 表示不限制
Max concurrent logins per account; -1 means unlimited
overflow_logout_mode: LogoutMode超出 max_login_count 时的下线模式
Logout mode used when max_login_count is exceeded
replaced_login_exit_mode: ReplacedLoginExitMode非并发顶号时:踢旧设备还是拒绝新登录 Non-concurrent replace policy: kick the old device or reject the new login
replaced_range: ReplacedRangeReplace scope on non-concurrent login (already enforced in AuthService). 非并发顶号范围(AuthService 已落地)。
right_now_create_token_session: bool登录时是否立即创建 Token-Session Whether to create a Token-Session immediately on login
token_session_check_login: bool获取 Token-Session 时是否校验 token 登录态 Whether fetching a Token-Session requires a valid login
logout_range: LogoutRangeDefault logout range: current token or entire account. 默认 logout 范围:当前 token 或整个账号。
is_logout_keep_token_session: boollogout 时是否保留 Token-Session Whether to keep the Token-Session on logout
grant_cache_ttl: i64权限/角色读缓存 TTL(秒)。<= 0 表示关闭缓存(默认),此时不分配任何缓存结构。
关闭是默认值的理由:多实例部署下缓存会带来「权限变更滞后」的安全窗口, 必须由使用者显式权衡后开启,而不是默认埋一个隐患。
TTL in seconds for the permission/role read cache. <= 0 disables the
cache entirely (default) and allocates nothing. Disabled by default
because a multi-instance deployment would otherwise silently inherit a
staleness window for authorization decisions.
grant_cache_max_entries: usize权限/角色缓存的总条目上限(跨全部分片)。达到上限时先清过期项, 仍超限则淘汰「最早过期」的一项,保证内存有界。
Global upper bound on cached entries across all shards. On overflow the cache first drops expired entries, then evicts the soonest-to-expire one, keeping memory bounded.
grant_cache_single_flight: bool是否启用单飞(single-flight):同一 key 并发未命中时只放行一次底层加载, 其余请求等待复用结果,避免缓存击穿打爆外部数据源。
Enables single-flight: concurrent misses on the same key trigger only one underlying load, preventing a cache stampede against the data source.
grant_request_scope: bool是否启用请求级授权快照:同一请求(SaTokenContext::scope)内多次鉴权
只读一次数据源。与 TTL 缓存不同,它随请求结束即销毁,没有一致性窗口,
因此默认开启。
Enables a per-request authorization snapshot so repeated checks inside one
SaTokenContext::scope hit the data source once. Unlike the TTL cache it
dies with the request, so there is no staleness window — hence on by default.
grant_write_policy: GrantWritePolicy注入只读 StpInterface 时的写策略,见 GrantWritePolicy。
Write policy when a read-only StpInterface is injected.
role_wildcard: boolWhen true, role checks honour * wildcards (default false = exact).
为 true 时角色校验识别 * 通配(默认 false,精确匹配)。
Enabling routes roles through the same segment matcher used for permissions.
context_auto_create: boolwith_current_mut 在无上下文时是否自动创建空上下文(默认 false,返回 None)
When true, with_current_mut auto-creates an empty context if none exists (fallback for
sync paths); when false (default), returns None to surface the programming error.
http_basic: StringHTTP Basic account in user:password form. Empty = caller must pass account.
HTTP Basic 账号,格式 user:password。空表示调用方必须传入 account。
same_token_timeout: i64Same-Token TTL in seconds; <= 0 means no TTL (storage-dependent).
Same-Token 有效期(秒);<= 0 表示不设 TTL。
same_token_header: StringHeader name for Same-Token. Same-Token 请求头名。
max_try_times: i32Max attempts when allocating a unique login / temp token. -1 = do not retry.
分配唯一登录/临时 token 的最大尝试次数。-1 表示不重试。
sign_secret_key: Option<String>HMAC secret for RequestSign via StpUtil (independent from JWT).
StpUtil 使用的 HMAC 密钥(与 JWT 密钥分离)。
sign_window_secs: i64Timestamp window in seconds for RequestSign (default 300).
RequestSign 的时间窗(秒),默认 300。
serializer: SharedSerializer存储层序列化器(默认 JSON;可选 fory;不参与本结构的 serde 序列化) Storage serializer (JSON by default; optional fory; skipped by this struct’s serde)
Implementations§
Source§impl SaTokenConfig
impl SaTokenConfig
Sourcepub fn builder() -> SaTokenConfigBuilder
pub fn builder() -> SaTokenConfigBuilder
创建配置构建器 | Create a configuration builder
Sourcepub fn timeout_duration(&self) -> Option<Duration>
pub fn timeout_duration(&self) -> Option<Duration>
将 timeout 转为 Duration;永久(< 0)时返回 None
Convert timeout to a Duration; returns None when permanent (< 0)
Sourcepub fn validate_jwt(&self) -> SaTokenResult<()>
pub fn validate_jwt(&self) -> SaTokenResult<()>
Reject Jwt style without a usable secret. Call from builders. Jwt 风格必须带可用密钥。由 builder 调用。
Sourcepub fn validate_token_io(&self) -> SaTokenResult<()>
pub fn validate_token_io(&self) -> SaTokenResult<()>
Reject unusable token-read / prefix combinations. 拒绝无法工作的读取开关 / 前缀组合。
Sourcepub fn grant_cache_duration(&self) -> Option<Duration>
pub fn grant_cache_duration(&self) -> Option<Duration>
权限缓存 TTL 的 Duration 形式;返回 None 表示不启用缓存。
The grant cache TTL as a Duration; None means the cache is disabled.
Sourcepub fn make_key(&self, suffix: &str, id: &str) -> String
👎Deprecated since 0.2.0: Use SaKeys named key methods (token_info / login_token / …) instead
pub fn make_key(&self, suffix: &str, id: &str) -> String
Use SaKeys named key methods (token_info / login_token / …) instead
构造存储键:拼接 storage_key_prefix 与后缀。
Build a storage key by joining storage_key_prefix and a suffix.
§Deprecated
请改用 [SaKeys] 具名方法,以尊重键布局策略。
Use [SaKeys] named methods instead so key layout is respected.
Sourcepub fn key_prefix(&self) -> &str
pub fn key_prefix(&self) -> &str
获取存储键前缀 | Get the storage key prefix
Sourcepub fn encode<T: Serialize + ?Sized>(&self, value: &T) -> SaTokenResult<String>
pub fn encode<T: Serialize + ?Sized>(&self, value: &T) -> SaTokenResult<String>
将领域对象编码为存储字符串 | Encode a domain object into a storage string
Sourcepub fn decode<T: DeserializeOwned>(&self, raw: &str) -> SaTokenResult<T>
pub fn decode<T: DeserializeOwned>(&self, raw: &str) -> SaTokenResult<T>
从存储字符串解码领域对象 | Decode a domain object from a storage string
Trait Implementations§
Source§impl Clone for SaTokenConfig
impl Clone for SaTokenConfig
Source§fn clone(&self) -> SaTokenConfig
fn clone(&self) -> SaTokenConfig
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more