Skip to main content

TokenAuthMiddleware

Struct TokenAuthMiddleware 

Source
pub struct TokenAuthMiddleware<F, V = NoopTokenClaimsValidator> { /* private fields */ }
Expand description

Token 鉴权中间件:在 Action 派发前完成 JWT 三重校验并注入当前用户。

挂到 ModuleSpec 后,只对非公开 Action 执行; 标记为 public 的 Action 会绕过本认证中间件,但仍会经过日志、限流、追踪等 通用中间件。对受保护 Action:

  1. 从 Request::token 取 Authorization: Bearer <token>; 缺失则短路返回 BaseError::Unauthorized。
  2. 调用 TokenManager::verify_token_checked 完成 签名 + 过期 + 黑名单 三重校验;失败短路(TokenVerifyFailed / TokenExpired / TokenRevoked 等原样上抛)。
  3. 用注入的 claims -> User 闭包,从已验证的 TokenClaims 构造 User 并填入 ActionContext.user,随后 next.run(ctx)。

用户如何从声明映射(角色/权限放在哪个自定义字段)因项目而异,故由闭包 F 注入。

§示例

ⓘ
use yang_base::action::{TokenAuthMiddleware, User};
use yang_base::definition::{ModuleName, ModuleSpec};

// 从 JWT sub 取用户 ID;业务标识解析失败时必须拒绝认证
let auth = TokenAuthMiddleware::new(|claims| {
    let id = claims.sub.parse::<i64>()
        .map_err(|_| yang_base::BaseError::Unauthorized("Token subject 无效".into()))?;
    Ok(User::new(id, claims.sub.clone()))
});

let module = ModuleSpec::new(ModuleName::new("account.user")?).middleware(auth);

Implementations§

Source§

impl<F, R> TokenAuthMiddleware<F, NoopTokenClaimsValidator>
where F: Fn(&TokenClaims) -> R + Send + Sync + 'static, R: IntoUserProjection,

Source

pub fn new(build_user: F) -> Self

用「声明 -> 用户」闭包创建 Token 鉴权中间件。

闭包可返回 User 保持简单场景兼容,也可返回 Result<User, BaseError>,在 subject、角色或权限声明格式非法时 fail-closed。

Source§

impl<F, V> TokenAuthMiddleware<F, V>

Source

pub fn with_claims_validator<N>( self, claims_validator: N, ) -> TokenAuthMiddleware<F, N>

注入应用级异步声明校验器,并保留同一条 Token 认证链。

Source

pub fn authenticate_public_actions(self) -> Self

在公开 Action 上启用可选认证。

默认情况下,本中间件只处理受保护 Action,以确保登录、刷新等公开端点不会 因缺少 Token 被拦截。启用本选项后,公开 Action 在没有 Authorization header 时仍按匿名请求继续;携带 Bearer Token 时则完成完整校验并注入用户。该模式 适用于请求级 UI 目录等“匿名可用、登录后按身份投影”的公开端点。

非 Bearer Authorization header、无效 Token 和错误 Token 类型不会降级为匿名。

Trait Implementations§

Source§

impl<F, R, V> Middleware for TokenAuthMiddleware<F, V>
where F: Fn(&TokenClaims) -> R + Send + Sync + 'static, R: IntoUserProjection + Send + Sync + 'static, V: TokenClaimsValidator,

Source§

fn role(&self) -> MiddlewareRole

返回构建期可验证的安全依赖角色。
Source§

fn scope(&self) -> MiddlewareScope

返回此中间件适用的 Action 范围。 Read more
Source§

fn handle<'life0, 'life1, 'async_trait>( &'life0 self, ctx: ActionContext, next: Next<'life1>, ) -> Pin<Box<dyn Future<Output = Result<ApiResponse, BaseError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

处理一次派发。 Read more
Source§

fn target_action(&self) -> Option<&ActionRef>

返回只应执行此中间件的确定 Action。 Read more

Auto Trait Implementations§

§

impl<F, V> Freeze for TokenAuthMiddleware<F, V>
where F: Freeze, V: Freeze,

§

impl<F, V> RefUnwindSafe for TokenAuthMiddleware<F, V>

§

impl<F, V> Send for TokenAuthMiddleware<F, V>
where F: Send, V: Send,

§

impl<F, V> Sync for TokenAuthMiddleware<F, V>
where F: Sync, V: Sync,

§

impl<F, V> Unpin for TokenAuthMiddleware<F, V>
where F: Unpin, V: Unpin,

§

impl<F, V> UnsafeUnpin for TokenAuthMiddleware<F, V>
where F: UnsafeUnpin, V: UnsafeUnpin,

§

impl<F, V> UnwindSafe for TokenAuthMiddleware<F, V>
where F: UnwindSafe, V: UnwindSafe,

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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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