google.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. //!
  2. //! This example showcases the Google OAuth2 process for requesting access to the Google Calendar features
  3. //! and the user's profile.
  4. //!
  5. //! Before running it, you'll need to generate your own Google OAuth2 credentials.
  6. //!
  7. //! In order to run the example call:
  8. //!
  9. //! ```sh
  10. //! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
  11. //! ```
  12. //!
  13. //! ...and follow the instructions.
  14. //!
  15. use oauth2::{basic::BasicClient, revocation::StandardRevocableToken, TokenResponse};
  16. // Alternatively, this can be oauth2::curl::http_client or a custom.
  17. use oauth2::reqwest::http_client;
  18. use oauth2::{
  19. AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
  20. RevocationUrl, Scope, TokenUrl,
  21. };
  22. use std::env;
  23. use std::io::{BufRead, BufReader, Write};
  24. use std::net::TcpListener;
  25. use url::Url;
  26. fn main() {
  27. let google_client_id = ClientId::new(
  28. env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
  29. );
  30. let google_client_secret = ClientSecret::new(
  31. env::var("GOOGLE_CLIENT_SECRET")
  32. .expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
  33. );
  34. let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
  35. .expect("Invalid authorization endpoint URL");
  36. let token_url = TokenUrl::new("https://www.googleapis.com/oauth2/v3/token".to_string())
  37. .expect("Invalid token endpoint URL");
  38. // Set up the config for the Google OAuth2 process.
  39. let client = BasicClient::new(
  40. google_client_id,
  41. Some(google_client_secret),
  42. auth_url,
  43. Some(token_url),
  44. )
  45. // This example will be running its own server at localhost:8080.
  46. // See below for the server implementation.
  47. .set_redirect_uri(
  48. RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
  49. )
  50. // Google supports OAuth 2.0 Token Revocation (RFC-7009)
  51. .set_revocation_uri(
  52. RevocationUrl::new("https://oauth2.googleapis.com/revoke".to_string())
  53. .expect("Invalid revocation endpoint URL"),
  54. );
  55. // Google supports Proof Key for Code Exchange (PKCE - https://oauth.net/2/pkce/).
  56. // Create a PKCE code verifier and SHA-256 encode it as a code challenge.
  57. let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
  58. // Generate the authorization URL to which we'll redirect the user.
  59. let (authorize_url, csrf_state) = client
  60. .authorize_url(CsrfToken::new_random)
  61. // This example is requesting access to the "calendar" features and the user's profile.
  62. .add_scope(Scope::new(
  63. "https://www.googleapis.com/auth/calendar".to_string(),
  64. ))
  65. .add_scope(Scope::new(
  66. "https://www.googleapis.com/auth/plus.me".to_string(),
  67. ))
  68. .set_pkce_challenge(pkce_code_challenge)
  69. .url();
  70. println!(
  71. "Open this URL in your browser:\n{}\n",
  72. authorize_url.to_string()
  73. );
  74. // A very naive implementation of the redirect server.
  75. let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
  76. for stream in listener.incoming() {
  77. if let Ok(mut stream) = stream {
  78. let code;
  79. let state;
  80. {
  81. let mut reader = BufReader::new(&stream);
  82. let mut request_line = String::new();
  83. reader.read_line(&mut request_line).unwrap();
  84. let redirect_url = request_line.split_whitespace().nth(1).unwrap();
  85. let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
  86. let code_pair = url
  87. .query_pairs()
  88. .find(|pair| {
  89. let &(ref key, _) = pair;
  90. key == "code"
  91. })
  92. .unwrap();
  93. let (_, value) = code_pair;
  94. code = AuthorizationCode::new(value.into_owned());
  95. let state_pair = url
  96. .query_pairs()
  97. .find(|pair| {
  98. let &(ref key, _) = pair;
  99. key == "state"
  100. })
  101. .unwrap();
  102. let (_, value) = state_pair;
  103. state = CsrfToken::new(value.into_owned());
  104. }
  105. let message = "Go back to your terminal :)";
  106. let response = format!(
  107. "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
  108. message.len(),
  109. message
  110. );
  111. stream.write_all(response.as_bytes()).unwrap();
  112. println!("Google returned the following code:\n{}\n", code.secret());
  113. println!(
  114. "Google returned the following state:\n{} (expected `{}`)\n",
  115. state.secret(),
  116. csrf_state.secret()
  117. );
  118. // Exchange the code with a token.
  119. let token_response = client
  120. .exchange_code(code)
  121. .set_pkce_verifier(pkce_code_verifier)
  122. .request(http_client);
  123. println!(
  124. "Google returned the following token:\n{:?}\n",
  125. token_response
  126. );
  127. // Revoke the obtained token
  128. let token_response = token_response.unwrap();
  129. let token_to_revoke: StandardRevocableToken = match token_response.refresh_token() {
  130. Some(token) => token.into(),
  131. None => token_response.access_token().into(),
  132. };
  133. client
  134. .revoke_token(token_to_revoke)
  135. .unwrap()
  136. .request(http_client)
  137. .expect("Failed to revoke token");
  138. // The server will terminate itself after revoking the token.
  139. break;
  140. }
  141. }
  142. }