google.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. //!
  2. //! This example showcases the process of integrating with the
  3. //! [Google OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect)
  4. //! provider.
  5. //!
  6. //! Before running it, you'll need to generate your own Google OAuth2 credentials.
  7. //!
  8. //! In order to run the example call:
  9. //!
  10. //! ```sh
  11. //! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
  12. //! ```
  13. //!
  14. //! ...and follow the instructions.
  15. //!
  16. use std::env;
  17. use std::io::{BufRead, BufReader, Write};
  18. use std::net::TcpListener;
  19. use std::process::exit;
  20. use serde::{Deserialize, Serialize};
  21. use url::Url;
  22. use openidconnect::core::{
  23. CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, CoreGrantType,
  24. CoreIdTokenClaims, CoreIdTokenVerifier, CoreJsonWebKey, CoreJsonWebKeyType, CoreJsonWebKeyUse,
  25. CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, CoreJwsSigningAlgorithm,
  26. CoreResponseMode, CoreResponseType, CoreRevocableToken, CoreSubjectIdentifierType,
  27. };
  28. use openidconnect::reqwest::http_client;
  29. use openidconnect::{
  30. AdditionalProviderMetadata, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret,
  31. CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, ProviderMetadata, RedirectUrl, RevocationUrl,
  32. Scope,
  33. };
  34. fn handle_error<T: std::error::Error>(fail: &T, msg: &'static str) {
  35. let mut err_msg = format!("ERROR: {}", msg);
  36. let mut cur_fail: Option<&dyn std::error::Error> = Some(fail);
  37. while let Some(cause) = cur_fail {
  38. err_msg += &format!("\n caused by: {}", cause);
  39. cur_fail = cause.source();
  40. }
  41. println!("{}", err_msg);
  42. exit(1);
  43. }
  44. // Teach openidconnect-rs about a Google custom extension to the OpenID Discovery response that we can use as the RFC
  45. // 7009 OAuth 2.0 Token Revocation endpoint. For more information about the Google specific Discovery response see the
  46. // Google OpenID Connect service documentation at: https://developers.google.com/identity/protocols/oauth2/openid-connect#discovery
  47. #[derive(Clone, Debug, Deserialize, Serialize)]
  48. struct RevocationEndpointProviderMetadata {
  49. revocation_endpoint: String,
  50. }
  51. impl AdditionalProviderMetadata for RevocationEndpointProviderMetadata {}
  52. type GoogleProviderMetadata = ProviderMetadata<
  53. RevocationEndpointProviderMetadata,
  54. CoreAuthDisplay,
  55. CoreClientAuthMethod,
  56. CoreClaimName,
  57. CoreClaimType,
  58. CoreGrantType,
  59. CoreJweContentEncryptionAlgorithm,
  60. CoreJweKeyManagementAlgorithm,
  61. CoreJwsSigningAlgorithm,
  62. CoreJsonWebKeyType,
  63. CoreJsonWebKeyUse,
  64. CoreJsonWebKey,
  65. CoreResponseMode,
  66. CoreResponseType,
  67. CoreSubjectIdentifierType,
  68. >;
  69. fn main() {
  70. env_logger::init();
  71. let google_client_id = ClientId::new(
  72. env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
  73. );
  74. let google_client_secret = ClientSecret::new(
  75. env::var("GOOGLE_CLIENT_SECRET")
  76. .expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
  77. );
  78. let issuer_url =
  79. IssuerUrl::new("https://accounts.google.com".to_string()).expect("Invalid issuer URL");
  80. // Fetch Google's OpenID Connect discovery document.
  81. //
  82. // Note: If we don't care about token revocation we can simply use CoreProviderMetadata here
  83. // instead of GoogleProviderMetadata. If instead we wanted to optionally use the token
  84. // revocation endpoint if it seems to be supported we could do something like this:
  85. // #[derive(Clone, Debug, Deserialize, Serialize)]
  86. // struct AllOtherProviderMetadata(HashMap<String, serde_json::Value>);
  87. // impl AdditionalClaims for AllOtherProviderMetadata {}
  88. // And then test for the presence of "revocation_endpoint" in the map returned by a call to
  89. // .additional_metadata().
  90. let provider_metadata = GoogleProviderMetadata::discover(&issuer_url, http_client)
  91. .unwrap_or_else(|err| {
  92. handle_error(&err, "Failed to discover OpenID Provider");
  93. unreachable!();
  94. });
  95. let revocation_endpoint = provider_metadata
  96. .additional_metadata()
  97. .revocation_endpoint
  98. .clone();
  99. println!(
  100. "Discovered Google revocation endpoint: {}",
  101. revocation_endpoint
  102. );
  103. // Set up the config for the Google OAuth2 process.
  104. let client = CoreClient::from_provider_metadata(
  105. provider_metadata,
  106. google_client_id,
  107. Some(google_client_secret),
  108. )
  109. // This example will be running its own server at localhost:8080.
  110. // See below for the server implementation.
  111. .set_redirect_uri(
  112. RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
  113. )
  114. // Google supports OAuth 2.0 Token Revocation (RFC-7009)
  115. .set_revocation_uri(
  116. RevocationUrl::new(revocation_endpoint).expect("Invalid revocation endpoint URL"),
  117. );
  118. // Generate the authorization URL to which we'll redirect the user.
  119. let (authorize_url, csrf_state, nonce) = client
  120. .authorize_url(
  121. AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
  122. CsrfToken::new_random,
  123. Nonce::new_random,
  124. )
  125. // This example is requesting access to the "calendar" features and the user's profile.
  126. .add_scope(Scope::new("email".to_string()))
  127. .add_scope(Scope::new("profile".to_string()))
  128. .url();
  129. println!("Open this URL in your browser:\n{}\n", authorize_url);
  130. // A very naive implementation of the redirect server.
  131. let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
  132. // Accept one connection
  133. let (mut stream, _) = listener.accept().unwrap();
  134. let code;
  135. let state;
  136. {
  137. let mut reader = BufReader::new(&stream);
  138. let mut request_line = String::new();
  139. reader.read_line(&mut request_line).unwrap();
  140. let redirect_url = request_line.split_whitespace().nth(1).unwrap();
  141. let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
  142. let code_pair = url
  143. .query_pairs()
  144. .find(|pair| {
  145. let &(ref key, _) = pair;
  146. key == "code"
  147. })
  148. .unwrap();
  149. let (_, value) = code_pair;
  150. code = AuthorizationCode::new(value.into_owned());
  151. let state_pair = url
  152. .query_pairs()
  153. .find(|pair| {
  154. let &(ref key, _) = pair;
  155. key == "state"
  156. })
  157. .unwrap();
  158. let (_, value) = state_pair;
  159. state = CsrfToken::new(value.into_owned());
  160. }
  161. let message = "Go back to your terminal :)";
  162. let response = format!(
  163. "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
  164. message.len(),
  165. message
  166. );
  167. stream.write_all(response.as_bytes()).unwrap();
  168. println!("Google returned the following code:\n{}\n", code.secret());
  169. println!(
  170. "Google returned the following state:\n{} (expected `{}`)\n",
  171. state.secret(),
  172. csrf_state.secret()
  173. );
  174. // Exchange the code with a token.
  175. let token_response = client
  176. .exchange_code(code)
  177. .request(http_client)
  178. .unwrap_or_else(|err| {
  179. handle_error(&err, "Failed to contact token endpoint");
  180. unreachable!();
  181. });
  182. println!(
  183. "Google returned access token:\n{}\n",
  184. token_response.access_token().secret()
  185. );
  186. println!("Google returned scopes: {:?}", token_response.scopes());
  187. let id_token_verifier: CoreIdTokenVerifier = client.id_token_verifier();
  188. let id_token_claims: &CoreIdTokenClaims = token_response
  189. .extra_fields()
  190. .id_token()
  191. .expect("Server did not return an ID token")
  192. .claims(&id_token_verifier, &nonce)
  193. .unwrap_or_else(|err| {
  194. handle_error(&err, "Failed to verify ID token");
  195. unreachable!();
  196. });
  197. println!("Google returned ID token: {:?}", id_token_claims);
  198. // Revoke the obtained token
  199. let token_to_revoke: CoreRevocableToken = match token_response.refresh_token() {
  200. Some(token) => token.into(),
  201. None => token_response.access_token().into(),
  202. };
  203. client
  204. .revoke_token(token_to_revoke)
  205. .expect("no revocation_uri configured")
  206. .request(http_client)
  207. .unwrap_or_else(|err| {
  208. handle_error(&err, "Failed to contact token revocation endpoint");
  209. unreachable!();
  210. });
  211. }