1 个不稳定版本
0.1.0 | 2024年5月29日 |
---|
#313 在 身份验证
12KB
169 行
msal-cert
msal-cert
是一个用于处理Microsoft身份验证库(MSAL)证书的Rust库。它提供了使用证书签名JWT令牌的功能,并使用客户端凭证从Azure Active Directory获取访问令牌。
目录
安装
将以下内容添加到您的 Cargo.toml
[dependencies]
msal-cert = "0.1.0"
使用
生成JWT令牌
您可以使用您的公钥和私钥生成JWT令牌。
use msal_cert::token::{Header, Payload};
use msal_cert::lib::acquire_token;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Your tenant ID and client ID
let tenant_id = "your_tenant_id".to_string();
let client_id = "your_client_id".to_string();
let scope = "your_scope".to_string();
// Load your private and public key PEM files
let private_key_pem = include_bytes!("../keys/private_key.pem").to_vec(); // Update with path to your private key
let public_key_pem = include_bytes!("../keys/public_key.pem").to_vec(); // Update with path to your public key
// Acquire token
let token_response = acquire_token(tenant_id, client_id, scope, &private_key_pem, &public_key_pem).await?;
println!("Access Token: {}", token_response.access_token);
Ok(())
}
定义头和负载
提供 Header
和 Payload
结构,以简化JWT令牌的创建
use msal_cert::token::{Header, Payload};
// Initialize Header
let public_key_pem = include_bytes!("../keys/public_key.pem").to_vec();
let header = Header::new(&public_key_pem)?;
// Initialize Payload
let tenant_id = "your_tenant_id".to_string();
let client_id = "your_client_id".to_string();
let payload = Payload::new(tenant_id.clone(), client_id.clone());
测试
使用以下命令运行测试
cargo test
注意:请确保您的密钥文件位于测试函数中指定的正确路径。
#[tokio::test]
#[ignore]
async fn test_acquire_token() -> Result<(), Box<dyn std::error::Error>> {
let tenant_id = "your_tenant_id".to_string();
let client_id = "your_client_id".to_string();
let scope = "your_scope".to_string();
let private_key_pem = include_bytes!("../keys/private_key.pem").to_vec();
let public_key_pem = include_bytes!("../keys/public_key.pem").to_vec();
let token_response = acquire_token(tenant_id, client_id, scope, &private_key_pem, &public_key_pem).await?;
assert_eq!(token_response.token_type, "Bearer");
assert!(token_response.expires_in > 0);
assert!(token_response.access_token.len() > 0);
Ok(())
}
许可证
本项目采用MIT许可证。有关详细信息,请参阅LICENSE 文件。
依赖关系
~8–23MB
~378K SLoC