OAuth2Manager

Struct OAuth2Manager 

Source
pub struct OAuth2Manager { /* private fields */ }
Expand description

OAuth2 Manager | OAuth2 管理器

Core manager for OAuth2 authorization code flow operations. OAuth2 授权码模式的核心管理器。

§Responsibilities | 职责

  • Client registration and verification | 客户端注册和验证
  • Authorization code generation and validation | 授权码生成和验证
  • Access token issuance and verification | 访问令牌颁发和验证
  • Refresh token management | 刷新令牌管理
  • Security validation (redirect URI, scope, etc.) | 安全验证(回调 URI、权限范围等)

Implementations§

Source§

impl OAuth2Manager

Source

pub fn new(storage: Arc<dyn SaStorage>) -> Self

Create a new OAuth2Manager with default TTL values 使用默认 TTL 值创建新的 OAuth2Manager

§Default TTL | 默认 TTL
  • Authorization code: 600 seconds (10 minutes) | 授权码:600 秒(10 分钟)
  • Access token: 3600 seconds (1 hour) | 访问令牌:3600 秒(1 小时)
  • Refresh token: 2592000 seconds (30 days) | 刷新令牌:2592000 秒(30 天)
§Arguments | 参数
  • storage - Storage backend for persistence | 用于持久化的存储后端
Source

pub fn with_ttl( self, code_ttl: i64, token_ttl: i64, refresh_token_ttl: i64, ) -> Self

Set custom TTL values for codes and tokens 设置授权码和令牌的自定义 TTL 值

§Arguments | 参数
  • code_ttl - Authorization code TTL in seconds | 授权码 TTL(秒)
  • token_ttl - Access token TTL in seconds | 访问令牌 TTL(秒)
  • refresh_token_ttl - Refresh token TTL in seconds | 刷新令牌 TTL(秒)
§Example | 示例
let oauth2 = OAuth2Manager::new(storage)
    .with_ttl(300, 1800, 604800); // 5min, 30min, 7days
Source

pub async fn register_client(&self, client: &OAuth2Client) -> SaTokenResult<()>

Register a new OAuth2 client | 注册新的 OAuth2 客户端

Stores client information in the backend for future authentication. 将客户端信息存储在后端,用于未来的认证。

§Arguments | 参数
  • client - Client information to register | 要注册的客户端信息
§Returns | 返回
  • Ok(()) on success | 成功时返回 Ok(())
  • Err(SaTokenError) on storage or serialization error | 存储或序列化错误时返回错误
§Example | 示例
let client = OAuth2Client {
    client_id: "app_001".to_string(),
    client_secret: "secret".to_string(),
    redirect_uris: vec!["http://localhost/callback".to_string()],
    grant_types: vec!["authorization_code".to_string()],
    scope: vec!["read".to_string(), "write".to_string()],
};
oauth2.register_client(&client).await?;
Source

pub async fn get_client(&self, client_id: &str) -> SaTokenResult<OAuth2Client>

Retrieve client information by client ID | 通过客户端 ID 检索客户端信息

§Arguments | 参数
  • client_id - Client identifier | 客户端标识符
§Returns | 返回
  • Ok(OAuth2Client) if found | 找到时返回客户端信息
  • Err(OAuth2ClientNotFound) if client doesn’t exist | 客户端不存在时返回错误
Source

pub async fn verify_client( &self, client_id: &str, client_secret: &str, ) -> SaTokenResult<bool>

Verify client credentials | 验证客户端凭据

Checks if the provided client_id and client_secret match. 检查提供的 client_id 和 client_secret 是否匹配。

§Arguments | 参数
  • client_id - Client identifier | 客户端标识符
  • client_secret - Client secret key | 客户端密钥
§Returns | 返回
  • Ok(true) if credentials are valid | 凭据有效时返回 true
  • Ok(false) if credentials are invalid | 凭据无效时返回 false
  • Err(OAuth2ClientNotFound) if client doesn’t exist | 客户端不存在时返回错误
Source

pub fn generate_authorization_code( &self, client_id: String, user_id: String, redirect_uri: String, scope: Vec<String>, ) -> AuthorizationCode

Generate a new authorization code | 生成新的授权码

Creates a temporary authorization code after user consent. 在用户同意后创建临时授权码。

§Arguments | 参数
  • client_id - Client requesting authorization | 请求授权的客户端
  • user_id - User granting authorization | 授予授权的用户
  • redirect_uri - Callback URI for this authorization | 此授权的回调 URI
  • scope - Granted permissions | 授予的权限
§Returns | 返回
  • AuthorizationCode with unique code and expiration | 带有唯一代码和过期时间的授权码
§Note | 注意

This code must be stored using store_authorization_code() before returning to client. 此代码必须在返回给客户端之前使用 store_authorization_code() 存储。

Source

pub async fn store_authorization_code( &self, auth_code: &AuthorizationCode, ) -> SaTokenResult<()>

Store authorization code in backend | 在后端存储授权码

Persists the authorization code with TTL for later exchange. 使用 TTL 持久化授权码,以便稍后交换。

§Arguments | 参数
  • auth_code - Authorization code to store | 要存储的授权码
§Storage Key Format | 存储键格式

oauth2:code:{authorization_code}

Source

pub async fn get_authorization_code( &self, code: &str, ) -> SaTokenResult<AuthorizationCode>

Retrieve authorization code information | 获取授权码信息

Fetches the stored authorization code and validates its expiration. 获取存储的授权码并验证其过期状态。

§Arguments | 参数
  • code - Authorization code to retrieve | 要获取的授权码
§Returns | 返回
  • Ok(AuthorizationCode) if code exists and is valid | 授权码存在且有效时返回
  • Err(OAuth2CodeNotFound) if code not found | 授权码未找到时
  • Err(TokenExpired) if code has expired | 授权码已过期时
§Note | 注意

Expired codes are automatically cleaned up from storage. 过期的授权码会自动从存储中清理。

Source

pub async fn consume_authorization_code( &self, code: &str, ) -> SaTokenResult<AuthorizationCode>

Consume authorization code (one-time use) | 消费授权码(一次性使用)

Retrieves and deletes the authorization code in one operation. 在一次操作中检索并删除授权码。

§Arguments | 参数
  • code - Authorization code to consume | 要消费的授权码
§Returns | 返回
  • Ok(AuthorizationCode) if code is valid and consumed | 授权码有效且已消费时返回
  • Err(OAuth2CodeNotFound) if code not found | 授权码未找到时
  • Err(TokenExpired) if code has expired | 授权码已过期时
§Security | 安全性

This ensures the code can only be used once, preventing replay attacks. 这确保授权码只能使用一次,防止重放攻击。

Source

pub async fn exchange_code_for_token( &self, code: &str, client_id: &str, client_secret: &str, redirect_uri: &str, ) -> SaTokenResult<AccessToken>

Exchange authorization code for access token | 用授权码换取访问令牌

Core of the authorization code flow. Validates the code and issues tokens. 授权码流程的核心。验证授权码并颁发令牌。

§Validations | 验证
  1. Client credentials (client_id + client_secret) | 客户端凭据
  2. Authorization code exists and not expired | 授权码存在且未过期
  3. Client ID matches the code | 客户端 ID 与授权码匹配
  4. Redirect URI matches the code | 回调 URI 与授权码匹配
§Arguments | 参数
  • code - Authorization code | 授权码
  • client_id - Client identifier | 客户端标识符
  • client_secret - Client secret | 客户端密钥
  • redirect_uri - Redirect URI used in authorization | 授权时使用的回调 URI
§Returns | 返回
  • Ok(AccessToken) with access_token and optional refresh_token | 带有访问令牌和可选刷新令牌
  • Err(OAuth2InvalidCredentials) if client credentials invalid | 客户端凭据无效时
  • Err(OAuth2CodeNotFound) if code not found or expired | 授权码未找到或已过期时
  • Err(OAuth2ClientIdMismatch) if client ID doesn’t match | 客户端 ID 不匹配时
  • Err(OAuth2RedirectUriMismatch) if redirect URI doesn’t match | 回调 URI 不匹配时
§Security | 安全性

The authorization code is consumed (deleted) after use to prevent replay attacks. 授权码在使用后被消费(删除),以防止重放攻击。

Source

pub async fn generate_access_token( &self, client_id: &str, user_id: &str, scope: Vec<String>, ) -> SaTokenResult<AccessToken>

Generate access token and refresh token | 生成访问令牌和刷新令牌

Creates a new access token with an optional refresh token for the user. 为用户创建新的访问令牌和可选的刷新令牌。

§Arguments | 参数
  • client_id - Client identifier | 客户端标识符
  • user_id - User identifier | 用户标识符
  • scope - Granted permissions | 授予的权限范围
§Returns | 返回
  • Ok(AccessToken) with access_token and refresh_token | 带有访问令牌和刷新令牌
§Storage | 存储
  • Access token: oauth2:token:{access_token} (TTL: token_ttl)
  • Refresh token: oauth2:refresh:{refresh_token} (TTL: refresh_token_ttl)
§Note | 注意

Both tokens are stored with TTL for automatic expiration cleanup. 两个令牌都使用 TTL 存储,以便自动清理过期令牌。

Source

pub async fn verify_access_token( &self, access_token: &str, ) -> SaTokenResult<OAuth2TokenInfo>

Verify access token and retrieve token information | 验证访问令牌并检索令牌信息

Checks if the access token is valid and not expired. 检查访问令牌是否有效且未过期。

§Arguments | 参数
  • access_token - Access token to verify | 要验证的访问令牌
§Returns | 返回
  • Ok(OAuth2TokenInfo) if token is valid | 令牌有效时返回令牌信息
  • Err(OAuth2AccessTokenNotFound) if token not found | 令牌未找到时
  • Err(TokenExpired) if token has expired | 令牌已过期时
§Note | 注意

Expired tokens are automatically cleaned up from storage. 过期的令牌会自动从存储中清理。

Source

pub async fn refresh_access_token( &self, refresh_token: &str, client_id: &str, client_secret: &str, ) -> SaTokenResult<AccessToken>

Refresh access token using refresh token | 使用刷新令牌刷新访问令牌

Issues a new access token (and optionally a new refresh token) when the old one expires. 当旧令牌过期时颁发新的访问令牌(以及可选的新刷新令牌)。

§Validations | 验证
  1. Client credentials are valid | 客户端凭据有效
  2. Refresh token exists and belongs to the client | 刷新令牌存在且属于该客户端
  3. Client ID matches the refresh token | 客户端 ID 与刷新令牌匹配
§Arguments | 参数
  • refresh_token - Refresh token | 刷新令牌
  • client_id - Client identifier | 客户端标识符
  • client_secret - Client secret | 客户端密钥
§Returns | 返回
  • Ok(AccessToken) with new access_token and refresh_token | 新的访问令牌和刷新令牌
  • Err(OAuth2InvalidCredentials) if credentials invalid | 凭据无效时
  • Err(OAuth2RefreshTokenNotFound) if refresh token not found | 刷新令牌未找到时
  • Err(OAuth2ClientIdMismatch) if client ID doesn’t match | 客户端 ID 不匹配时
Source

pub async fn revoke_token(&self, token: &str) -> SaTokenResult<()>

Revoke an access token or refresh token | 撤销访问令牌或刷新令牌

Deletes the token from storage, making it immediately invalid. 从存储中删除令牌,使其立即失效。

§Arguments | 参数
  • token - Token to revoke (access or refresh) | 要撤销的令牌(访问或刷新)
§Use Cases | 使用场景
  • User logout | 用户登出
  • Security breach | 安全漏洞
  • Client revocation | 客户端撤销
Source

pub fn validate_redirect_uri( &self, client: &OAuth2Client, redirect_uri: &str, ) -> bool

Validate redirect URI against client’s whitelist | 根据客户端白名单验证回调 URI

Security check to prevent redirect URI hijacking. 安全检查以防止回调 URI 劫持。

§Arguments | 参数
  • client - Client information with registered URIs | 带有注册 URI 的客户端信息
  • redirect_uri - URI to validate | 要验证的 URI
§Returns | 返回
  • true if URI is in the whitelist | URI 在白名单中时返回 true
  • false if URI is not allowed | URI 不被允许时返回 false
Source

pub fn validate_scope( &self, client: &OAuth2Client, requested_scope: &[String], ) -> bool

Validate requested scopes against client’s permitted scopes | 根据客户端允许的范围验证请求的权限范围

Ensures requested scopes are a subset of client’s permitted scopes. 确保请求的权限范围是客户端允许范围的子集。

§Arguments | 参数
  • client - Client information with permitted scopes | 带有允许权限范围的客户端信息
  • requested_scope - Scopes being requested | 正在请求的权限范围
§Returns | 返回
  • true if all requested scopes are permitted | 所有请求的权限范围都被允许时返回 true
  • false if any requested scope is not permitted | 任何请求的权限范围不被允许时返回 false

Auto Trait Implementations§

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

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
§

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

§

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> Same for T

Source§

type Output = T

Should always be Self
§

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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

Performs the conversion.
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