Skip to main content

SaTokenConfig

Struct SaTokenConfig 

Source
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: String

Token 名称(header / cookie / body 中的键名) Token name (key used in header, cookie, or body)

§timeout: i64

Token 有效期(秒),-1 表示永久有效 Token lifetime in seconds; -1 means never expires

§active_timeout: i64

Token 最低活跃频率(秒),-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: bool

Per-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; default 300)

Only effective when auto_renew == true.

§is_concurrent: bool

是否允许同一账号并发登录 Whether the same account may log in concurrently

§is_share: bool

Concurrent logins share one token when true (default false). 为 true 时同一账号并发登录共用一个 token(默认 false)。

§token_style: TokenStyle

Token 风格(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

§is_read_cookie: bool

是否从 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: TokenCookieConfig

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: bool

JWT 生成失败时是否回退为 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: i64

Nonce 有效期(秒),-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: i64

Refresh 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: ReplacedRange

Replace 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: LogoutRange

Default logout range: current token or entire account. 默认 logout 范围:当前 token 或整个账号。

§is_logout_keep_token_session: bool

logout 时是否保留 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: bool

When true, role checks honour * wildcards (default false = exact). 为 true 时角色校验识别 * 通配(默认 false,精确匹配)。

Enabling routes roles through the same segment matcher used for permissions.

§context_auto_create: bool

with_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: String

HTTP Basic account in user:password form. Empty = caller must pass account. HTTP Basic 账号,格式 user:password。空表示调用方必须传入 account。

§same_token_timeout: i64

Same-Token TTL in seconds; <= 0 means no TTL (storage-dependent). Same-Token 有效期(秒);<= 0 表示不设 TTL。

§same_token_header: String

Header name for Same-Token. Same-Token 请求头名。

§max_try_times: i32

Max 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: i64

Timestamp 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

Source

pub fn builder() -> SaTokenConfigBuilder

创建配置构建器 | Create a configuration builder

Source

pub fn timeout_duration(&self) -> Option<Duration>

将 timeout 转为 Duration;永久(< 0)时返回 None Convert timeout to a Duration; returns None when permanent (< 0)

Source

pub fn validate_jwt(&self) -> Result<(), SaTokenError>

Reject Jwt style without a usable secret. Call from builders. Jwt 风格必须带可用密钥。由 builder 调用。

Source

pub fn validate_token_io(&self) -> Result<(), SaTokenError>

Reject unusable token-read / prefix combinations. 拒绝无法工作的读取开关 / 前缀组合。

Source

pub fn grant_cache_duration(&self) -> Option<Duration>

权限缓存 TTL 的 Duration 形式;返回 None 表示不启用缓存。

The grant cache TTL as a Duration; None means the cache is disabled.

Source

pub fn make_key(&self, suffix: &str, id: &str) -> String

👎Deprecated since 0.2.0:

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.

Source

pub fn key_prefix(&self) -> &str

获取存储键前缀 | Get the storage key prefix

Source

pub fn encode<T>(&self, value: &T) -> Result<String, SaTokenError>
where T: Serialize + ?Sized,

将领域对象编码为存储字符串 | Encode a domain object into a storage string

Source

pub fn decode<T>(&self, raw: &str) -> Result<T, SaTokenError>

从存储字符串解码领域对象 | Decode a domain object from a storage string

Trait Implementations§

Source§

impl Clone for SaTokenConfig

Source§

fn clone(&self) -> SaTokenConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SaTokenConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for SaTokenConfig

Source§

fn default() -> SaTokenConfig

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for SaTokenConfig

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<SaTokenConfig, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for SaTokenConfig

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more