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
impl OAuth2Manager
Sourcepub fn new(storage: Arc<dyn SaStorage>) -> OAuth2Manager
pub fn new(storage: Arc<dyn SaStorage>) -> OAuth2Manager
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 | 用于持久化的存储后端
Sourcepub fn with_ttl(
self,
code_ttl: i64,
token_ttl: i64,
refresh_token_ttl: i64,
) -> OAuth2Manager
pub fn with_ttl( self, code_ttl: i64, token_ttl: i64, refresh_token_ttl: i64, ) -> OAuth2Manager
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, 7daysSourcepub async fn register_client(
&self,
client: &OAuth2Client,
) -> Result<(), SaTokenError>
pub async fn register_client( &self, client: &OAuth2Client, ) -> Result<(), SaTokenError>
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?;Sourcepub async fn get_client(
&self,
client_id: &str,
) -> Result<OAuth2Client, SaTokenError>
pub async fn get_client( &self, client_id: &str, ) -> Result<OAuth2Client, SaTokenError>
Sourcepub async fn verify_client(
&self,
client_id: &str,
client_secret: &str,
) -> Result<bool, SaTokenError>
pub async fn verify_client( &self, client_id: &str, client_secret: &str, ) -> Result<bool, SaTokenError>
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 | 凭据有效时返回trueOk(false)if credentials are invalid | 凭据无效时返回falseErr(OAuth2ClientNotFound)if client doesn’t exist | 客户端不存在时返回错误
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 | 此授权的回调 URIscope- Granted permissions | 授予的权限
§Returns | 返回
AuthorizationCodewith unique code and expiration | 带有唯一代码和过期时间的授权码
§Note | 注意
This code must be stored using store_authorization_code() before returning to client.
此代码必须在返回给客户端之前使用 store_authorization_code() 存储。
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. 过期的授权码会自动从存储中清理。
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. 这确保授权码只能使用一次,防止重放攻击。
Sourcepub async fn exchange_code_for_token(
&self,
code: &str,
client_id: &str,
client_secret: &str,
redirect_uri: &str,
) -> Result<AccessToken, SaTokenError>
pub async fn exchange_code_for_token( &self, code: &str, client_id: &str, client_secret: &str, redirect_uri: &str, ) -> Result<AccessToken, SaTokenError>
Exchange authorization code for access token | 用授权码换取访问令牌
Core of the authorization code flow. Validates the code and issues tokens. 授权码流程的核心。验证授权码并颁发令牌。
§Validations | 验证
- Client credentials (client_id + client_secret) | 客户端凭据
- Authorization code exists and not expired | 授权码存在且未过期
- Client ID matches the code | 客户端 ID 与授权码匹配
- 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. 授权码在使用后被消费(删除),以防止重放攻击。
Sourcepub async fn generate_access_token(
&self,
client_id: &str,
user_id: &str,
scope: Vec<String>,
) -> Result<AccessToken, SaTokenError>
pub async fn generate_access_token( &self, client_id: &str, user_id: &str, scope: Vec<String>, ) -> Result<AccessToken, SaTokenError>
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 存储,以便自动清理过期令牌。
Sourcepub async fn verify_access_token(
&self,
access_token: &str,
) -> Result<OAuth2TokenInfo, SaTokenError>
pub async fn verify_access_token( &self, access_token: &str, ) -> Result<OAuth2TokenInfo, SaTokenError>
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. 过期的令牌会自动从存储中清理。
Sourcepub async fn refresh_access_token(
&self,
refresh_token: &str,
client_id: &str,
client_secret: &str,
) -> Result<AccessToken, SaTokenError>
pub async fn refresh_access_token( &self, refresh_token: &str, client_id: &str, client_secret: &str, ) -> Result<AccessToken, SaTokenError>
Refresh access token using refresh token | 使用刷新令牌刷新访问令牌
Issues a new access token (and optionally a new refresh token) when the old one expires. 当旧令牌过期时颁发新的访问令牌(以及可选的新刷新令牌)。
§Validations | 验证
- Client credentials are valid | 客户端凭据有效
- Refresh token exists and belongs to the client | 刷新令牌存在且属于该客户端
- 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 不匹配时
Sourcepub async fn revoke_token(&self, token: &str) -> Result<(), SaTokenError>
pub async fn revoke_token(&self, token: &str) -> Result<(), SaTokenError>
Sourcepub fn validate_redirect_uri(
&self,
client: &OAuth2Client,
redirect_uri: &str,
) -> bool
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 | 返回
trueif URI is in the whitelist | URI 在白名单中时返回truefalseif URI is not allowed | URI 不被允许时返回false
Sourcepub fn validate_scope(
&self,
client: &OAuth2Client,
requested_scope: &[String],
) -> bool
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 | 返回
trueif all requested scopes are permitted | 所有请求的权限范围都被允许时返回truefalseif any requested scope is not permitted | 任何请求的权限范围不被允许时返回false
Auto Trait Implementations§
impl Freeze for OAuth2Manager
impl !RefUnwindSafe for OAuth2Manager
impl Send for OAuth2Manager
impl Sync for OAuth2Manager
impl Unpin for OAuth2Manager
impl !UnwindSafe for OAuth2Manager
Blanket Implementations§
§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moreSource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);