Skip to content
This repository was archived by the owner on Oct 6, 2020. It is now read-only.

Commit b20f8a0

Browse files
committed
Switched aad to full async
1 parent a605363 commit b20f8a0

File tree

9 files changed

+268
-137
lines changed

9 files changed

+268
-137
lines changed

Diff for: azure_sdk_auth_aad/Cargo.toml

+16-19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "azure_sdk_auth_aad"
3-
version = "0.21.1"
3+
version = "0.22.0"
44
description = "Rust wrappers around Microsoft Azure REST APIs - Azure OAuth2 helper crate"
55
readme = "README.md"
66
authors = ["Francesco Cogno <[email protected]>"]
@@ -15,24 +15,21 @@ categories = ["api-bindings"]
1515
edition = "2018"
1616

1717
[dependencies]
18-
azure_sdk_core = { path = "../azure_sdk_core", version = "0.20.2" }
19-
oauth2 = "3.0.0-alpha.4"
20-
base64 = "0.10.1"
21-
url = "2.1.0"
22-
rand = "0.7.2"
23-
failure = "0.1.6"
24-
futures = "0.1.29"
25-
hyper = "0.12.35"
26-
hyper-rustls = "0.16.1"
27-
http = "0.1.19"
28-
serde = "1.0.101"
29-
serde_derive = "1.0.101"
30-
chrono = "0.4.9"
31-
serde_json = "1.0.41"
32-
log = "0.4.8"
33-
34-
[dev-dependencies]
35-
tokio-core = "0.1.17"
18+
azure_sdk_core = { path = "../azure_sdk_core", version = "0.20.4" }
19+
oauth2 = "3.0.0-alpha.4"
20+
base64 = "0.10.1"
21+
url = "2.1.0"
22+
rand = "0.7.2"
23+
failure = "0.1.6"
24+
futures-core-preview = { version = "=0.3.0-alpha.19" }
25+
futures-preview = { version = "=0.3.0-alpha.19", features = ["compat", "async-await"] }
26+
http = "0.1.19"
27+
serde = "1.0.101"
28+
serde_derive = "1.0.101"
29+
chrono = "0.4.9"
30+
serde_json = "1.0.41"
31+
log = "0.4.8"
32+
reqwest = "0.10.0-alpha.1"
3633

3734
[features]
3835
test_e2e = []

Diff for: azure_sdk_auth_aad/examples/interactive.rs

+48-27
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
11
use azure_sdk_auth_aad::*;
2-
use azure_sdk_core::perform_http_request;
3-
use futures::future::{ok, Future};
4-
use hyper::{Body, Client, Request};
2+
use futures::executor::block_on;
53
use oauth2::{ClientId, ClientSecret, TokenResponse};
64
use std::env;
7-
use std::sync::Arc;
8-
use tokio_core::reactor::Core;
95
use url::Url;
106

117
fn main() {
12-
let client_id = ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable."));
13-
let client_secret = ClientSecret::new(env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."));
14-
let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable.");
15-
let subscription_id = env::var("SUBSCRIPTION_ID").expect("Missing SUBSCRIPTION_ID environment variable.");
8+
block_on(main_async());
9+
}
1610

17-
let mut core = Core::new().unwrap();
18-
let client: Client<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>> =
19-
hyper::Client::builder().build(hyper_rustls::HttpsConnector::new(4));
20-
let client = Arc::new(client);
11+
async fn main_async() {
12+
let client_id =
13+
ClientId::new(env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable."));
14+
let client_secret = ClientSecret::new(
15+
env::var("CLIENT_SECRET").expect("Missing CLIENT_SECRET environment variable."),
16+
);
17+
let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable.");
18+
let subscription_id =
19+
env::var("SUBSCRIPTION_ID").expect("Missing SUBSCRIPTION_ID environment variable.");
2120

2221
// Create URL to browse for initial authorization
2322
let c = authorize_delegate(
@@ -32,35 +31,57 @@ fn main() {
3231
println!("\nbrowse this url:\n{}", c.authorize_url);
3332

3433
// Start a naive server to receive the redirect
35-
// with the token
34+
// with the token. This naive server is blocking
35+
// so you should use something better.
3636
let code = naive_server(&c, 3003).unwrap();
3737

3838
println!("code received: {:?}", code);
3939

4040
// Exchange the token with one that can be
4141
// used for authorization
42-
let token = exchange(c, code).unwrap();
42+
let token = exchange(c, code).await.unwrap();
4343

4444
println!("token received: {:?}", token);
4545

4646
// Let's enumerate the Azure SQL Databases instances
4747
// in the subscription. Note: this way of calling the REST API
4848
// will be different (and easier) using other Azure Rust SDK
4949
// crates, this is just an example.
50-
let request = Request::builder()
51-
.method("GET")
52-
.header("Authorization", format!("Bearer {}", token.access_token().secret()))
53-
// .uri(format!("https://management.azure.com/subscriptions/{}/resourcegroups?api-version=2017-05-10", subscription_id))
54-
.uri(format!(
50+
let url = Url::parse(&format!(
5551
"https://management.azure.com/subscriptions/{}/providers/Microsoft.Sql/servers?api-version=2015-05-01-preview",
5652
subscription_id
57-
))
58-
.body(Body::from(""))
53+
)).unwrap();
54+
55+
let resp = reqwest::Client::new()
56+
.get(url)
57+
.header(
58+
"Authorization",
59+
format!("Bearer {}", token.access_token().secret()),
60+
)
61+
.send()
62+
.await
63+
.unwrap()
64+
.text()
65+
.await
5966
.unwrap();
6067

61-
let fut = perform_http_request(&client, request, http::status::StatusCode::OK).and_then(|resp| {
62-
println!("\n\nresp {:?}", resp);
63-
ok(())
64-
});
65-
core.run(fut).unwrap();
68+
println!("\n\nresp {:?}", resp);
69+
70+
//let request = Request::builder()
71+
// .method("GET")
72+
// .header("Authorization", format!("Bearer {}", token.access_token().secret()))
73+
// // .uri(format!("https://management.azure.com/subscriptions/{}/resourcegroups?api-version=2017-05-10", subscription_id))
74+
// .uri(format!(
75+
// "https://management.azure.com/subscriptions/{}/providers/Microsoft.Sql/servers?api-version=2015-05-01-preview",
76+
// subscription_id
77+
// ))
78+
// .body(Body::from(""))
79+
// .unwrap();
80+
81+
//let fut =
82+
// perform_http_request(&client, request, http::status::StatusCode::OK).and_then(|resp| {
83+
// println!("\n\nresp {:?}", resp);
84+
// ok(())
85+
// });
86+
//core.run(fut).unwrap();
6687
}

Diff for: azure_sdk_auth_aad/src/lib.rs

+49-34
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,24 @@ extern crate failure;
44
extern crate serde_derive;
55
extern crate log;
66
use azure_sdk_core::errors::AzureError;
7-
use futures::future::{done, ok, Future};
87
use log::debug;
98
use oauth2::basic::BasicClient;
10-
use oauth2::reqwest::http_client;
9+
use oauth2::reqwest::async_http_client;
1110
use oauth2::{
12-
AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, TokenUrl,
11+
AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge,
12+
PkceCodeVerifier, RedirectUrl, TokenUrl,
1313
};
1414
use std::str::FromStr;
1515
use url::form_urlencoded;
1616
use url::Url;
1717
mod login_response;
18-
use azure_sdk_core::perform_http_request;
19-
use http::status::StatusCode;
20-
use hyper::{Body, Client, Request};
2118
pub use login_response::*;
2219
use std::sync::Arc;
2320
pub mod errors;
2421
mod naive_server;
22+
use futures::compat::Future01CompatExt;
2523
pub use naive_server::naive_server;
24+
use reqwest;
2625

2726
#[derive(Debug)]
2827
pub struct AuthObj {
@@ -32,13 +31,26 @@ pub struct AuthObj {
3231
pub pkce_code_verifier: PkceCodeVerifier,
3332
}
3433

35-
pub fn authorize_delegate(client_id: ClientId, client_secret: ClientSecret, tenant_id: &str, redirect_url: Url, resource: &str) -> AuthObj {
34+
pub fn authorize_delegate(
35+
client_id: ClientId,
36+
client_secret: ClientSecret,
37+
tenant_id: &str,
38+
redirect_url: Url,
39+
resource: &str,
40+
) -> AuthObj {
3641
let auth_url = AuthUrl::new(
37-
Url::parse(&format!("https://login.microsoftonline.com/{}/oauth2/authorize", tenant_id))
38-
.expect("Invalid authorization endpoint URL"),
42+
Url::parse(&format!(
43+
"https://login.microsoftonline.com/{}/oauth2/authorize",
44+
tenant_id
45+
))
46+
.expect("Invalid authorization endpoint URL"),
3947
);
4048
let token_url = TokenUrl::new(
41-
Url::parse(&format!("https://login.microsoftonline.com/{}/oauth2/v2.0/token", tenant_id)).expect("Invalid token endpoint URL"),
49+
Url::parse(&format!(
50+
"https://login.microsoftonline.com/{}/oauth2/v2.0/token",
51+
tenant_id
52+
))
53+
.expect("Invalid token endpoint URL"),
4254
);
4355

4456
// Set up the config for the Microsoft Graph OAuth2 process.
@@ -67,56 +79,59 @@ pub fn authorize_delegate(client_id: ClientId, client_secret: ClientSecret, tena
6779
}
6880
}
6981

70-
pub fn exchange(
82+
pub async fn exchange(
7183
auth_obj: AuthObj,
7284
code: AuthorizationCode,
7385
) -> Result<
7486
oauth2::StandardTokenResponse<oauth2::EmptyExtraTokenFields, oauth2::basic::BasicTokenType>,
75-
oauth2::RequestTokenError<oauth2::reqwest::Error, oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>>,
87+
oauth2::RequestTokenError<
88+
oauth2::reqwest::Error,
89+
oauth2::StandardErrorResponse<oauth2::basic::BasicErrorResponseType>,
90+
>,
7691
> {
7792
// Exchange the code with a token.
7893
let token = auth_obj
7994
.client
8095
.exchange_code(code)
8196
// Send the PKCE code verifier in the token request
8297
.set_pkce_verifier(auth_obj.pkce_code_verifier)
83-
.request(http_client);
98+
.request_async(async_http_client)
99+
.compat()
100+
.await?;
84101

85102
debug!("MS Graph returned the following token:\n{:?}\n", token);
86-
token
103+
Ok(token)
87104
}
88105

89-
pub fn authorize_non_interactive(
90-
client: Arc<Client<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>>>,
106+
pub async fn authorize_non_interactive(
107+
client: Arc<reqwest::Client>,
91108
// grant_type: &str, fixed on "client_credentials",
92109
client_id: &oauth2::ClientId,
93110
client_secret: &oauth2::ClientSecret,
94111
resource: &str,
95112
tenant_id: &str,
96-
) -> impl Future<Item = LoginResponse, Error = AzureError> {
113+
) -> Result<LoginResponse, AzureError> {
97114
let encoded: String = form_urlencoded::Serializer::new(String::new())
98115
.append_pair("grant_type", "client_credentials")
99116
.append_pair("client_id", client_id.as_str())
100117
.append_pair("client_secret", client_secret.secret())
101118
.append_pair("resource", resource)
102119
.finish();
103120

104-
let uri = format!("https://login.microsoftonline.com/{}/oauth2/token", tenant_id);
121+
let url = url::Url::parse(&format!(
122+
"https://login.microsoftonline.com/{}/oauth2/token",
123+
tenant_id
124+
))
125+
.map_err(|error| AzureError::GenericErrorWithText(error.to_string()))?;
126+
127+
let resp = client
128+
.post(url)
129+
.header("ContentType", "Application / WwwFormUrlEncoded")
130+
.body(encoded)
131+
.send()
132+
.await?
133+
.text()
134+
.await?;
105135

106-
done(
107-
Request::builder()
108-
.method("POST")
109-
.header("ContentType", "Application / WwwFormUrlEncoded")
110-
.uri(uri)
111-
.body(Body::from(encoded)),
112-
)
113-
.from_err()
114-
.and_then(move |request| {
115-
perform_http_request(&client, request, StatusCode::OK).and_then(|resp| {
116-
done(LoginResponse::from_str(&resp)).from_err().and_then(|r| {
117-
debug!("{:?}", r);
118-
ok(r)
119-
})
120-
})
121-
})
136+
Ok(LoginResponse::from_str(&resp)?)
122137
}

Diff for: azure_sdk_core/Cargo.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "azure_sdk_core"
3-
version = "0.20.3"
3+
version = "0.20.4"
44
description = "Rust wrappers around Microsoft Azure REST APIs - Core crate"
55
readme = "README.md"
66
authors = ["Francesco Cogno <[email protected]>", "Max Gortman <[email protected]>", "Dong Liu <[email protected]>"]
@@ -37,6 +37,7 @@ uuid = { version = "0.7", features = ["v4"] }
3737
smallvec = { version = "0.6", features = ["serde"] }
3838
bytes = "0.4"
3939
hyper-rustls = "0.16"
40+
reqwest = "0.10.0-alpha.1"
4041

4142
[dev-dependencies]
4243
tokio-core = "0.1"

0 commit comments

Comments
 (0)