File: microsoft_devicecode_tenant_user.rs

package info (click to toggle)
rust-oauth2 5.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 656 kB
  • sloc: makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use oauth2::basic::BasicClient;
use oauth2::reqwest;
use oauth2::StandardDeviceAuthorizationResponse;
use oauth2::{AuthUrl, ClientId, DeviceAuthorizationUrl, Scope, TokenUrl};

use std::error::Error;

// Reference: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code
// Please use your tenant id when using this example
const TENANT_ID: &str = "{tenant}";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = BasicClient::new(ClientId::new("client_id".to_string()))
        .set_auth_uri(AuthUrl::new(format!(
            "https://login.microsoftonline.com/{}/oauth2/v2.0/authorize",
            TENANT_ID
        ))?)
        .set_token_uri(TokenUrl::new(format!(
            "https://login.microsoftonline.com/{}/oauth2/v2.0/token",
            TENANT_ID
        ))?)
        .set_device_authorization_url(DeviceAuthorizationUrl::new(format!(
            "https://login.microsoftonline.com/{}/oauth2/v2.0/devicecode",
            TENANT_ID
        ))?);

    let http_client = reqwest::ClientBuilder::new()
        // Following redirects opens the client up to SSRF vulnerabilities.
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .expect("Client should build");

    let details: StandardDeviceAuthorizationResponse = client
        .exchange_device_code()
        .add_scope(Scope::new("read".to_string()))
        .request_async(&http_client)
        .await?;

    eprintln!(
        "Open this URL in your browser:\n{}\nand enter the code: {}",
        details.verification_uri(),
        details.user_code().secret(),
    );

    let token_result = client
        .exchange_device_access_token(&details)
        .request_async(&http_client, tokio::time::sleep, None)
        .await;

    eprintln!("Token:{token_result:?}");

    Ok(())
}