123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240 |
- //!
- //! This example showcases the process of integrating with the
- //! [Google OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect)
- //! provider.
- //!
- //! Before running it, you'll need to generate your own Google OAuth2 credentials.
- //!
- //! In order to run the example call:
- //!
- //! ```sh
- //! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
- //! ```
- //!
- //! ...and follow the instructions.
- //!
- use std::env;
- use std::io::{BufRead, BufReader, Write};
- use std::net::TcpListener;
- use std::process::exit;
- use serde::{Deserialize, Serialize};
- use url::Url;
- use openidconnect::core::{
- CoreAuthDisplay, CoreClaimName, CoreClaimType, CoreClient, CoreClientAuthMethod, CoreGrantType,
- CoreIdTokenClaims, CoreIdTokenVerifier, CoreJsonWebKey, CoreJsonWebKeyType, CoreJsonWebKeyUse,
- CoreJweContentEncryptionAlgorithm, CoreJweKeyManagementAlgorithm, CoreJwsSigningAlgorithm,
- CoreResponseMode, CoreResponseType, CoreRevocableToken, CoreSubjectIdentifierType,
- };
- use openidconnect::reqwest::http_client;
- use openidconnect::{
- AdditionalProviderMetadata, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret,
- CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, ProviderMetadata, RedirectUrl, RevocationUrl,
- Scope,
- };
- fn handle_error<T: std::error::Error>(fail: &T, msg: &'static str) {
- let mut err_msg = format!("ERROR: {}", msg);
- let mut cur_fail: Option<&dyn std::error::Error> = Some(fail);
- while let Some(cause) = cur_fail {
- err_msg += &format!("\n caused by: {}", cause);
- cur_fail = cause.source();
- }
- println!("{}", err_msg);
- exit(1);
- }
- // Teach openidconnect-rs about a Google custom extension to the OpenID Discovery response that we can use as the RFC
- // 7009 OAuth 2.0 Token Revocation endpoint. For more information about the Google specific Discovery response see the
- // Google OpenID Connect service documentation at: https://developers.google.com/identity/protocols/oauth2/openid-connect#discovery
- #[derive(Clone, Debug, Deserialize, Serialize)]
- struct RevocationEndpointProviderMetadata {
- revocation_endpoint: String,
- }
- impl AdditionalProviderMetadata for RevocationEndpointProviderMetadata {}
- type GoogleProviderMetadata = ProviderMetadata<
- RevocationEndpointProviderMetadata,
- CoreAuthDisplay,
- CoreClientAuthMethod,
- CoreClaimName,
- CoreClaimType,
- CoreGrantType,
- CoreJweContentEncryptionAlgorithm,
- CoreJweKeyManagementAlgorithm,
- CoreJwsSigningAlgorithm,
- CoreJsonWebKeyType,
- CoreJsonWebKeyUse,
- CoreJsonWebKey,
- CoreResponseMode,
- CoreResponseType,
- CoreSubjectIdentifierType,
- >;
- fn main() {
- env_logger::init();
- let google_client_id = ClientId::new(
- env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
- );
- let google_client_secret = ClientSecret::new(
- env::var("GOOGLE_CLIENT_SECRET")
- .expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
- );
- let issuer_url =
- IssuerUrl::new("https://accounts.google.com".to_string()).expect("Invalid issuer URL");
- // Fetch Google's OpenID Connect discovery document.
- //
- // Note: If we don't care about token revocation we can simply use CoreProviderMetadata here
- // instead of GoogleProviderMetadata. If instead we wanted to optionally use the token
- // revocation endpoint if it seems to be supported we could do something like this:
- // #[derive(Clone, Debug, Deserialize, Serialize)]
- // struct AllOtherProviderMetadata(HashMap<String, serde_json::Value>);
- // impl AdditionalClaims for AllOtherProviderMetadata {}
- // And then test for the presence of "revocation_endpoint" in the map returned by a call to
- // .additional_metadata().
- let provider_metadata = GoogleProviderMetadata::discover(&issuer_url, http_client)
- .unwrap_or_else(|err| {
- handle_error(&err, "Failed to discover OpenID Provider");
- unreachable!();
- });
- let revocation_endpoint = provider_metadata
- .additional_metadata()
- .revocation_endpoint
- .clone();
- println!(
- "Discovered Google revocation endpoint: {}",
- revocation_endpoint
- );
- // Set up the config for the Google OAuth2 process.
- let client = CoreClient::from_provider_metadata(
- provider_metadata,
- google_client_id,
- Some(google_client_secret),
- )
- // This example will be running its own server at localhost:8080.
- // See below for the server implementation.
- .set_redirect_uri(
- RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
- )
- // Google supports OAuth 2.0 Token Revocation (RFC-7009)
- .set_revocation_uri(
- RevocationUrl::new(revocation_endpoint).expect("Invalid revocation endpoint URL"),
- );
- // Generate the authorization URL to which we'll redirect the user.
- let (authorize_url, csrf_state, nonce) = client
- .authorize_url(
- AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
- CsrfToken::new_random,
- Nonce::new_random,
- )
- // This example is requesting access to the "calendar" features and the user's profile.
- .add_scope(Scope::new("email".to_string()))
- .add_scope(Scope::new("profile".to_string()))
- .url();
- println!("Open this URL in your browser:\n{}\n", authorize_url);
- // A very naive implementation of the redirect server.
- let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
- // Accept one connection
- let (mut stream, _) = listener.accept().unwrap();
- let code;
- let state;
- {
- let mut reader = BufReader::new(&stream);
- let mut request_line = String::new();
- reader.read_line(&mut request_line).unwrap();
- let redirect_url = request_line.split_whitespace().nth(1).unwrap();
- let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
- let code_pair = url
- .query_pairs()
- .find(|pair| {
- let &(ref key, _) = pair;
- key == "code"
- })
- .unwrap();
- let (_, value) = code_pair;
- code = AuthorizationCode::new(value.into_owned());
- let state_pair = url
- .query_pairs()
- .find(|pair| {
- let &(ref key, _) = pair;
- key == "state"
- })
- .unwrap();
- let (_, value) = state_pair;
- state = CsrfToken::new(value.into_owned());
- }
- let message = "Go back to your terminal :)";
- let response = format!(
- "HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
- message.len(),
- message
- );
- stream.write_all(response.as_bytes()).unwrap();
- println!("Google returned the following code:\n{}\n", code.secret());
- println!(
- "Google returned the following state:\n{} (expected `{}`)\n",
- state.secret(),
- csrf_state.secret()
- );
- // Exchange the code with a token.
- let token_response = client
- .exchange_code(code)
- .request(http_client)
- .unwrap_or_else(|err| {
- handle_error(&err, "Failed to contact token endpoint");
- unreachable!();
- });
- println!(
- "Google returned access token:\n{}\n",
- token_response.access_token().secret()
- );
- println!("Google returned scopes: {:?}", token_response.scopes());
- let id_token_verifier: CoreIdTokenVerifier = client.id_token_verifier();
- let id_token_claims: &CoreIdTokenClaims = token_response
- .extra_fields()
- .id_token()
- .expect("Server did not return an ID token")
- .claims(&id_token_verifier, &nonce)
- .unwrap_or_else(|err| {
- handle_error(&err, "Failed to verify ID token");
- unreachable!();
- });
- println!("Google returned ID token: {:?}", id_token_claims);
- // Revoke the obtained token
- let token_to_revoke: CoreRevocableToken = match token_response.refresh_token() {
- Some(token) => token.into(),
- None => token_response.access_token().into(),
- };
- client
- .revoke_token(token_to_revoke)
- .expect("no revocation_uri configured")
- .request(http_client)
- .unwrap_or_else(|err| {
- handle_error(&err, "Failed to contact token revocation endpoint");
- unreachable!();
- });
- }
|