3个版本
0.1.2 | 2021年7月4日 |
---|---|
0.1.1 | 2020年12月18日 |
0.1.0 | 2020年12月17日 |
1008 在 认证
7KB
53 代码行
oauth2-surf
使用surf HTTP客户端的oauth2crate HTTP客户端适配器
文档可在docs.rs上找到
lib.rs
:
使用surf HTTP客户端的oauth2crate HTTP客户端适配器
用法
只需从本库导入http_client
函数,并在交换令牌时将其传递给request_async函数。(示例来自oauth2文档)
use anyhow;
use oauth2::{
AuthorizationCode,
AuthUrl,
ClientId,
ClientSecret,
CsrfToken,
PkceCodeChallenge,
RedirectUrl,
Scope,
TokenResponse,
TokenUrl
};
use oauth2::basic::BasicClient;
use oauth2_surf::http_client;
use url::Url;
// Create an OAuth2 client by specifying the client ID, client secret, authorization URL and
// token URL.
let client =
BasicClient::new(
ClientId::new("client_id".to_string()),
Some(ClientSecret::new("client_secret".to_string())),
AuthUrl::new("http://authorize".to_string())?,
Some(TokenUrl::new("http://token".to_string())?)
)
// Set the URL the user will be redirected to after the authorization process.
.set_redirect_url(RedirectUrl::new("http://redirect".to_string())?);
// Generate a PKCE challenge.
let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
// Generate the full authorization URL.
let (auth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
// Set the desired scopes.
.add_scope(Scope::new("read".to_string()))
.add_scope(Scope::new("write".to_string()))
// Set the PKCE code challenge.
.set_pkce_challenge(pkce_challenge)
.url();
// This is the URL you should redirect the user to, in order to trigger the authorization
// process.
println!("Browse to: {}", auth_url);
// Once the user has been redirected to the redirect URL, you'll have access to the
// authorization code. For security reasons, your code should verify that the `state`
// parameter returned by the server matches `csrf_state`.
// Now you can trade it for an access token.
let token_result = client
.exchange_code(AuthorizationCode::new("some authorization code".to_string()))
// Set the PKCE code verifier.
.set_pkce_verifier(pkce_verifier)
.request_async(http_client)
.await?;
// Unwrapping token_result will either produce a Token or a RequestTokenError.
依赖项
~9–18MB
~247K SLoC