msgraph.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. //!
  2. //! This example showcases the Microsoft Graph OAuth2 process for requesting access to Microsoft
  3. //! services using PKCE.
  4. //!
  5. //! Before running it, you'll need to generate your own Microsoft OAuth2 credentials. See
  6. //! https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app
  7. //! * Register a `Web` application with a `Redirect URI` of `http://localhost:3003/redirect`.
  8. //! * In the left menu select `Overview`. Copy the `Application (client) ID` as the MSGRAPH_CLIENT_ID.
  9. //! * In the left menu select `Certificates & secrets` and add a new client secret. Copy the secret value
  10. //! as MSGRAPH_CLIENT_SECRET.
  11. //! * In the left menu select `API permissions` and add a permission. Select Microsoft Graph and
  12. //! `Delegated permissions`. Add the `Files.Read` permission.
  13. //!
  14. //! In order to run the example call:
  15. //!
  16. //! ```sh
  17. //! MSGRAPH_CLIENT_ID=xxx MSGRAPH_CLIENT_SECRET=yyy cargo run --example msgraph
  18. //! ```
  19. //!
  20. //! ...and follow the instructions.
  21. //!
  22. use oauth2::basic::BasicClient;
  23. // Alternatively, this can be `oauth2::curl::http_client` or a custom client.
  24. use oauth2::reqwest::http_client;
  25. use oauth2::{
  26. AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge,
  27. RedirectUrl, Scope, TokenUrl,
  28. };
  29. use std::env;
  30. use std::io::{BufRead, BufReader, Write};
  31. use std::net::TcpListener;
  32. use url::Url;
  33. fn main() {
  34. let graph_client_id = ClientId::new(
  35. env::var("MSGRAPH_CLIENT_ID").expect("Missing the MSGRAPH_CLIENT_ID environment variable."),
  36. );
  37. let graph_client_secret = ClientSecret::new(
  38. env::var("MSGRAPH_CLIENT_SECRET")
  39. .expect("Missing the MSGRAPH_CLIENT_SECRET environment variable."),
  40. );
  41. let auth_url =
  42. AuthUrl::new("https://login.microsoftonline.com/common/oauth2/v2.0/authorize".to_string())
  43. .expect("Invalid authorization endpoint URL");
  44. let token_url =
  45. TokenUrl::new("https://login.microsoftonline.com/common/oauth2/v2.0/token".to_string())
  46. .expect("Invalid token endpoint URL");
  47. // Set up the config for the Microsoft Graph OAuth2 process.
  48. let client = BasicClient::new(
  49. graph_client_id,
  50. Some(graph_client_secret),
  51. auth_url,
  52. Some(token_url),
  53. )
  54. // Microsoft Graph requires client_id and client_secret in URL rather than
  55. // using Basic authentication.
  56. .set_auth_type(AuthType::RequestBody)
  57. // This example will be running its own server at localhost:3003.
  58. // See below for the server implementation.
  59. .set_redirect_uri(
  60. RedirectUrl::new("http://localhost:3003/redirect".to_string())
  61. .expect("Invalid redirect URL"),
  62. );
  63. // Microsoft Graph supports Proof Key for Code Exchange (PKCE - https://oauth.net/2/pkce/).
  64. // Create a PKCE code verifier and SHA-256 encode it as a code challenge.
  65. let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
  66. // Generate the authorization URL to which we'll redirect the user.
  67. let (authorize_url, csrf_state) = client
  68. .authorize_url(CsrfToken::new_random)
  69. // This example requests read access to OneDrive.
  70. .add_scope(Scope::new(
  71. "https://graph.microsoft.com/Files.Read".to_string(),
  72. ))
  73. .set_pkce_challenge(pkce_code_challenge)
  74. .url();
  75. println!(
  76. "Open this URL in your browser:\n{}\n",
  77. authorize_url.to_string()
  78. );
  79. // A very naive implementation of the redirect server.
  80. let listener = TcpListener::bind("127.0.0.1:3003").unwrap();
  81. for stream in listener.incoming() {
  82. if let Ok(mut stream) = stream {
  83. let code;
  84. let state;
  85. {
  86. let mut reader = BufReader::new(&stream);
  87. let mut request_line = String::new();
  88. reader.read_line(&mut request_line).unwrap();
  89. let redirect_url = request_line.split_whitespace().nth(1).unwrap();
  90. let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
  91. let code_pair = url
  92. .query_pairs()
  93. .find(|pair| {
  94. let &(ref key, _) = pair;
  95. key == "code"
  96. })
  97. .unwrap();
  98. let (_, value) = code_pair;
  99. code = AuthorizationCode::new(value.into_owned());
  100. let state_pair = url
  101. .query_pairs()
  102. .find(|pair| {
  103. let &(ref key, _) = pair;
  104. key == "state"
  105. })
  106. .unwrap();
  107. let (_, value) = state_pair;
  108. state = CsrfToken::new(value.into_owned());
  109. }
  110. let message = "Go back to your terminal :)";
  111. let response = format!(
  112. "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
  113. message.len(),
  114. message
  115. );
  116. stream.write_all(response.as_bytes()).unwrap();
  117. println!("MS Graph returned the following code:\n{}\n", code.secret());
  118. println!(
  119. "MS Graph returned the following state:\n{} (expected `{}`)\n",
  120. state.secret(),
  121. csrf_state.secret()
  122. );
  123. // Exchange the code with a token.
  124. let token = client
  125. .exchange_code(code)
  126. // Send the PKCE code verifier in the token request
  127. .set_pkce_verifier(pkce_code_verifier)
  128. .request(http_client);
  129. println!("MS Graph returned the following token:\n{:?}\n", token);
  130. // The server will terminate itself after collecting the first code.
  131. break;
  132. }
  133. }
  134. }