8个版本 (5个破坏性更新)
0.8.0 | 2024年4月17日 |
---|---|
0.7.0 | 2023年11月10日 |
0.6.0 | 2023年11月1日 |
0.5.4 | 2023年10月31日 |
0.3.1 | 2022年9月27日 |
#292 在 认证
每月171次下载
35KB
709 行
gauth
该库支持以下Google认证流程
[dependencies]
gauth = "0.8"
OAuth2
- 在Google API控制台创建您的应用程序
a.凭证
>创建凭证
>OAuth客户端ID
b. 将应用程序类型设置为其他
c. 输入您的应用程序名称
d.下载新创建的应用程序的JSON
配置
具有默认值的客户端实现
use gauth::app::Auth;
#[tokio::main]
async fn main() {
let auth_client = Auth::from_file(
"my_credentials.json",
vec!["https://www.googleapis.com/auth/drive"],
)
.unwrap();
let token = auth_client.access_token().await.unwrap();
println!("access token: {}", token);
}
还可以进行阻塞调用以检索访问令牌。如果我们要将逻辑包装到闭包中,这可能很有用。
[dependencies]
gauth = { version = "0.8", features = ["app-blocking"] }
use gauth::app::Auth;
#[tokio::main]
async fn main() {
let ga = Auth::from_file(
"client_secret.json",
vec!["https://www.googleapis.com/auth/drive"]
).unwrap();
let closure = move || {
// add some logic here
ga.access_token_blocking()
};
let token = closure().unwrap();
println!("token from closure: {}", token);
}
自定义应用程序名称和处理程序:访问令牌将存储在$HOME/.{app_name}/access_token.json
要将自定义目录作为访问令牌缓存,设置环境变量值:GAUTH_TOKEN_DIR
use gauth::app::Auth;
use anyhow::Error as AnyError;
#[tokio::main]
async fn main() {
let auth_handler = |consent_uri: String| -> Result<String, AnyError> {
// business logic
Ok("auth_code".to_owned())
};
let mut auth_client = Auth::from_file(
"my_credentials.json",
vec!["https://www.googleapis.com/auth/drive"],
)
.unwrap();
let auth_client = auth_client.app_name("new_name").handler(auth_handler);
let token = auth_client.access_token().await.unwrap();
println!("access token: {}", token);
}
服务帐户
按照创建服务帐户的说明操作。创建服务帐户密钥后,可以使用它来获取访问令牌。
use gauth::serv_account::ServiceAccount;
#[tokio::main]
async fn access_token() {
let scopes = vec!["https://www.googleapis.com/auth/drive"];
let key_path = "test_fixtures/service-account-key.json";
let mut service_account = ServiceAccount::from_file(key_path, scopes);
let access_token = service_account.access_token().await.unwrap();
println!("access token {}:", access_token);
}
同步和异步代码的桥梁
此库中获取访问令牌的默认实现是异步的。但是,存在需要同步调用的场景。例如,当与tonic中间件一起使用时,异步签名可能会很繁琐。同步和异步代码集成的困难在此GitHub问题中概述。
为了解决这个问题,我们采用了一种实验性的方法,通过开发一个 token_provider
包来解决问题。此包包含一个 Watcher
特性,该特性已针对 app
和 serv_account
包实现。该特性的每个实现都会启动一个守护进程,该守护进程会定期以指定的时间间隔轮询和缓存令牌更新。因此,通过异步过程持续刷新令牌。令牌的检索简化为从内部缓存中读取的同步函数。
[dependencies]
gauth = { version = "0.8", features = ["token-watcher"] }
let service_account = ServiceAccount::from_file(&keypath, vec!["https://www.googleapis.com/auth/pubsub"]);
let tp = AsyncTokenProvider::new(service_account).with_interval(5);
// the token is updated every 5 seconds
// and cached in AsyncTokenProvider
tp.watch_updates().await;
// sync call to get the access token
let access_token = tp.access_token()?;
完整的示例可以在 这里 找到。
许可证
以下任一许可证下
依赖关系
~10–26MB
~454K SLoC