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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! # rocket_oauth2
//!
//! OAuth2 ([RFC 6749](https://tools.ietf.org/html/rfc6749)) for
//! [Rocket](https://rocket.rs) applications.
//!
//! ## Requirements
//!
//! * Rocket 0.4
//!
//! ## API Stability
//!
//! `rocket_oauth2` is still in its early stages and the API is subject to heavy
//! change in the future. semver is respsected, but only the latest release will
//! be actively maintained.
//!
//! ## Features
//!
//! * Handles the Authorization Code Grant (RFC 6749, §4.1)
//! * Built-in support for a few popular OAuth2 providers
//! * Support for custom providers
//! * Support for custom adapters
//! * Refreshing tokens
//!
//! ## Not-yet-planned Features
//!
//! * Grant types other than Authorization Code.
//!
//! ## Overview
//!
//! This crate provides two request guards: [`OAuth2`] and [`TokenResponse`].
//! `OAuth2` is used to generate redirects to to authentication providers, and
//! `TokenResponse` is employed on the application's Redirect URI route to
//! complete the token exchange.
//!
//! The [`Adapter`] trait defines how the temporary code from the authorization
//! server is exchanged for an authentication token. `rocket_oauth2` currently
//! provides only one `Adapter`, using
//! [`hyper-sync-rustls`](https://github.com/SergioBenitez/hyper-sync-rustls).
//!
//! If necessary a custom `Adapter` can be used, for example to work around
//! a noncompliant authorization server.
//!
//! ## Usage
//!
//! Configure your OAuth client settings in `Rocket.toml`:
//! ```toml
//! [global.oauth.github]
//! provider = "GitHub"
//! client_id = "..."
//! client_secret = "..."
//! redirect_uri = "http://localhost:8000/auth/github"
//! ```
//!
//! Implement routes for a login URI and a redirect URI. Mount these routes
//! and attach the [OAuth2 Fairing](OAuth2::fairing()):
//!
//! ```rust,no_run
//! # #![feature(proc_macro_hygiene, decl_macro)]
//! # #[macro_use] extern crate rocket;
//! # extern crate rocket_oauth2;
//! # use rocket::http::{Cookie, Cookies, SameSite};
//! # use rocket::Request;
//! # use rocket::response::Redirect;
//! use rocket_oauth2::{OAuth2, TokenResponse};
//!
//! // This struct will only be used as a type-level key. Multiple
//! // instances of OAuth2 can be used in the same application by
//! // using different key types.
//! struct GitHub;
//!
//! // This route calls `get_redirect`, which sets up a token request and
//! // returns a `Redirect` to the authorization endpoint.
//! #[get("/login/github")]
//! fn github_login(oauth2: OAuth2<GitHub>, mut cookies: Cookies<'_>) -> Redirect {
//!     // We want the "user:read" scope. For some providers, scopes may be
//!     // pre-selected or restricted during application registration. We could
//!     // use `&[]` instead to not request any scopes, but usually scopes
//!     // should be requested during registation, in the redirect, or both.
//!     oauth2.get_redirect(&mut cookies, &["user:read"]).unwrap()
//! }
//!
//! // This route, mounted at the application's Redirect URI, uses the
//! // `TokenResponse` request guard to complete the token exchange and obtain
//! // the token.
//! //
//! // The order is important here! If Cookies is positioned before
//! // TokenResponse, TokenResponse will be unable to verify the token exchange
//! // and return a failure.
//! #[get("/auth/github")]
//! fn github_callback(token: TokenResponse<GitHub>, mut cookies: Cookies<'_>) -> Redirect
//! {
//!     // Set a private cookie with the access token
//!     cookies.add_private(
//!         Cookie::build("token", token.access_token().to_string())
//!             .same_site(SameSite::Lax)
//!             .finish()
//!     );
//!     Redirect::to("/")
//! }
//!
//! fn main() {
//!     rocket::ignite()
//!         .mount("/", routes![github_callback, github_login])
//!         // The string "github" here matches [global.oauth2.github] in `Rocket.toml`
//!         .attach(OAuth2::<GitHub>::fairing("github"))
//!         .launch();
//! }
//! ```
//!
//! ### Provider selection
//!
//! Providers can be specified as a known provider name (case-insensitive).  The
//! known provider names are listed as associated constants on the
//! [`StaticProvider`] type.
//!
//! ```toml
//! [global.oauth.github]
//! # Using a known provider name
//! provider = "GitHub"
//! client_id = "..."
//! client_secret = "..."
//! redirect_uri = "http://localhost:8000/auth/github"
//! ```
//!
//! The provider can also be specified as a table with `auth_uri` and
//! `token_uri` values:
//!
//! ```toml
//! [global.oauth.custom]
//! provider = { auth_uri = "https://example.com/oauth/authorize", token_uri = "https://example.com/oauth/token" }
//! client_id = "..."
//! client_secret = "..."
//! redirect_uri = "http://localhost:8000/auth/custom"
//! ```

#![warn(future_incompatible, nonstandard_style, missing_docs)]
#![allow(clippy::needless_doctest_main)] // used intentionally for illustrative purposes

mod config;
mod error;

#[cfg(feature = "hyper_sync_rustls_adapter")]
mod hyper_sync_rustls_adapter;
#[cfg(feature = "hyper_sync_rustls_adapter")]
pub use hyper_sync_rustls_adapter::HyperSyncRustlsAdapter;

pub use self::config::*;
pub use self::error::*;

use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

use log::{error, warn};
use rocket::fairing::{AdHoc, Fairing};
use rocket::http::uri::Absolute;
use rocket::http::{Cookie, Cookies, SameSite, Status};
use rocket::request::{self, FormItems, FromForm, FromRequest, Request};
use rocket::response::Redirect;
use rocket::{Outcome, State};
use serde_json::Value;

const STATE_COOKIE_NAME: &str = "rocket_oauth2_state";

// Random generation of state for defense against CSRF.
// See RFC 6749 §10.12 for more details.
fn generate_state(rng: &mut impl rand::RngCore) -> Result<String, Error> {
    let mut buf = [0; 16]; // 128 bits
    rng.try_fill_bytes(&mut buf).map_err(|_| {
        Error::new_from(
            ErrorKind::Other,
            String::from("Failed to generate random data"),
        )
    })?;
    Ok(base64::encode_config(&buf, base64::URL_SAFE_NO_PAD))
}

/// The token types which can be exchanged with the token endpoint
#[derive(Clone, PartialEq, Debug)]
pub enum TokenRequest {
    /// Used for the Authorization Code exchange
    AuthorizationCode(String),
    /// Used to refresh an access token
    RefreshToken(String),
}

/// The server's response to a successful token exchange, defined in
/// in RFC 6749 §5.1.
///
/// `TokenResponse<K>` implements `FromRequest`, and is used in the callback
/// route to complete the token exchange. Since `TokenResponse` accesses
/// [`Cookies`], it must be positioned *before* `Cookies` in routes.
/// For more information, see [the rocket.rs guide].
///
/// # Example
///
/// ```rust
/// # #![feature(proc_macro_hygiene, decl_macro)]
/// # #[macro_use] extern crate rocket;
/// # use rocket::http::Cookies;
/// # use rocket::response::Redirect;
/// # struct Auth;
/// use rocket_oauth2::TokenResponse;
///
/// // Bad! This will fail at runtime:
/// // "Error: Multiple `Cookies` instances are active at once."
/// #[get("/auth")]
/// fn auth_callback(mut cookies: Cookies<'_>, token: TokenResponse<Auth>) -> Redirect {
///      // ...
/// #    Redirect::to("/")
/// }
/// ```
///
/// ```rust
/// # #![feature(proc_macro_hygiene, decl_macro)]
/// # #[macro_use] extern crate rocket;
/// # use rocket::http::Cookies;
/// # use rocket::response::Redirect;
/// # struct Auth;
/// use rocket_oauth2::TokenResponse;
///
/// // Good. TokenResponse will access and then release Cookies,
/// // and then both TokenResponse and Cookies will be given to the route.
/// #[get("/auth")]
/// fn auth_callback(token: TokenResponse<Auth>, mut cookies: Cookies<'_>) -> Redirect {
///      // ...
/// #    Redirect::to("/")
/// }
/// ```
///
/// [`Cookies`]: https://api.rocket.rs/v0.4/rocket/http/enum.Cookies.html
/// [the rocket.rs guide]: https://rocket.rs/v0.4/guide/requests/#one-at-a-time
#[derive(Clone, PartialEq, Debug)]
pub struct TokenResponse<K> {
    data: Value,
    _k: PhantomData<fn() -> K>,
}

impl<K> TokenResponse<K> {
    /// Reinterpret this `TokenResponse` as if it were keyed by `L` instead.
    /// This function can be used to treat disparate `TokenResponse`s as a
    /// single concrete type such as `TokenResponse<()>` to avoid an explosion
    /// of generic bounds.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// fn use_nongeneric_token(token: TokenResponse<()>) {
    ///     // ...
    /// }
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     use_nongeneric_token(token.cast());
    /// }
    /// ```
    pub fn cast<L>(self) -> TokenResponse<L> {
        TokenResponse {
            data: self.data,
            _k: PhantomData,
        }
    }

    /// Get the TokenResponse data as a raw JSON [Value]. It is guaranteed to
    /// be of type Object.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct MyProvider;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<MyProvider>) {
    ///     let custom_data = token.as_value().get("custom_data").unwrap().as_str();
    /// }
    /// ```
    pub fn as_value(&self) -> &Value {
        &self.data
    }

    /// Get the access token issued by the authorization server.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     let access_token = token.access_token();
    /// }
    /// ```
    pub fn access_token(&self) -> &str {
        self.data
            .get("access_token")
            .and_then(Value::as_str)
            .expect("access_token required at construction")
    }

    /// Get the type of token, described in RFC 6749 §7.1.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     let token_type = token.token_type();
    /// }
    /// ```
    pub fn token_type(&self) -> &str {
        self.data
            .get("token_type")
            .and_then(Value::as_str)
            .expect("token_type required at construction")
    }

    /// Get the lifetime in seconds of the access token, if the authorization server provided one.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     if let Some(expires_in) = token.expires_in() {
    ///         println!("Token expires in {} seconds", expires_in);
    ///     }
    /// }
    /// ```
    pub fn expires_in(&self) -> Option<i64> {
        self.data.get("expires_in").and_then(Value::as_i64)
    }

    /// Get the refresh token, if the server provided one.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     if let Some(refresh_token) = token.refresh_token() {
    ///         println!("Got a refresh token! '{}'", refresh_token);
    ///     }
    /// }
    /// ```
    pub fn refresh_token(&self) -> Option<&str> {
        self.data.get("refresh_token").and_then(Value::as_str)
    }

    /// Get the (space-separated) list of scopes associated with the access
    /// token.  The authorization server is required to provide this if it
    /// differs from the requested set of scopes.
    ///
    /// If `scope` was not provided by the server as a string, this method will
    /// return `None`. For those providers, use `.as_value().get("scope")
    /// instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::TokenResponse;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn login_github(token: TokenResponse<GitHub>) {
    ///     if let Some(scope) = token.scope() {
    ///         println!("Token scope: '{}'", scope);
    ///     }
    /// }
    /// ```
    pub fn scope(&self) -> Option<&str> {
        self.data.get("scope").and_then(Value::as_str)
    }
}

impl std::convert::TryFrom<Value> for TokenResponse<()> {
    type Error = Error;

    /// Construct a TokenResponse from a [Value].
    ///
    /// Returns an [Error] if data is not a JSON Object, or the access_token or token_type is
    /// missing or not a string.
    fn try_from(data: Value) -> Result<Self, Error> {
        if !data.is_object() {
            return Err(Error::new_from(
                ErrorKind::ExchangeFailure,
                String::from("TokenResponse data was not an object"),
            ));
        }
        match data.get("access_token") {
            Some(val) if val.is_string() => (),
            _ => {
                return Err(Error::new_from(
                    ErrorKind::ExchangeFailure,
                    String::from("TokenResponse access_token was missing or not a string"),
                ))
            }
        }
        match data.get("token_type") {
            Some(val) if val.is_string() => (),
            _ => {
                return Err(Error::new_from(
                    ErrorKind::ExchangeFailure,
                    String::from("TokenResponse token_type was missing or not a string"),
                ))
            }
        }

        Ok(Self {
            data,
            _k: PhantomData,
        })
    }
}

impl<'a, 'r, K: 'static> FromRequest<'a, 'r> for TokenResponse<K> {
    type Error = Error;

    // TODO: Decide if BadRequest is the appropriate error code.
    // TODO: What do providers do if they *reject* the authorization?
    /// Handle the redirect callback, delegating to the Adapter to perform the
    /// token exchange.
    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        let oauth2 = request
            .guard::<State<Arc<Shared<K>>>>()
            .expect("OAuth2 fairing was not attached for this key type!")
            .inner();

        // Parse the query data.
        let query = match request.uri().query() {
            Some(q) => q,
            None => {
                return Outcome::Failure((
                    Status::BadRequest,
                    Error::new_from(
                        ErrorKind::ExchangeFailure,
                        "Missing query string in request",
                    ),
                ))
            }
        };

        #[derive(FromForm)]
        struct CallbackQuery {
            code: String,
            state: String,
            // Nonstandard (but see below)
            scope: Option<String>,
        }

        let params = match CallbackQuery::from_form(&mut FormItems::from(query), false) {
            Ok(p) => p,
            Err(e) => {
                warn!("Failed to parse OAuth2 query string: {:?}", e);
                return Outcome::Failure((
                    Status::BadRequest,
                    Error::new_from(ErrorKind::ExchangeFailure, format!("{:?}", e)),
                ));
            }
        };

        {
            // Verify that the given state is the same one in the cookie.
            // Begin a new scope so that cookies is not kept around too long.
            let mut cookies = request.guard::<Cookies<'_>>().expect("request cookies");
            match cookies.get_private(STATE_COOKIE_NAME) {
                Some(ref cookie) if cookie.value() == params.state => {
                    cookies.remove(cookie.clone());
                }
                other => {
                    if other.is_some() {
                        warn!("The OAuth2 state returned from the server did not match the stored state.");
                    } else {
                        error!("The OAuth2 state cookie was missing. It may have been blocked by the client, \
                                or perhaps a `Cookies` guard is already active?");
                    }

                    return Outcome::Failure((
                        Status::BadRequest,
                        Error::new_from(
                            ErrorKind::ExchangeFailure,
                            "The OAuth2 state returned from the server did match the stored state.",
                        ),
                    ));
                }
            }
        }

        // Have the adapter perform the token exchange.
        match oauth2
            .adapter
            .exchange_code(&oauth2.config, TokenRequest::AuthorizationCode(params.code))
        {
            Ok(mut token) => {
                // Some providers (at least Strava) provide 'scope' in the callback
                // parameters instead of the token response as the RFC prescribes.
                // Therefore the 'scope' from the callback params is used as a fallback
                // if the token response does not specify one.
                let data = token
                    .data
                    .as_object_mut()
                    .expect("data is guaranteed to be an Object");
                if let (None, Some(scope)) = (data.get("scope"), params.scope) {
                    data.insert(String::from("scope"), Value::String(scope));
                }
                Outcome::Success(token.cast())
            }
            Err(e) => {
                warn!("OAuth2 token exchange failed: {}", e);
                Outcome::Failure((Status::BadRequest, e))
            }
        }
    }
}

/// An OAuth2 `Adapater` can be implemented by any type that facilitates the
/// Authorization Code Grant as described in RFC 6749 §4.1. The implementing
/// type must be able to generate an authorization URI and perform the token
/// exchange.
pub trait Adapter: Send + Sync + 'static {
    /// Generate an authorization URI as described by RFC 6749 §4.1.1 given
    /// configuration, state, and scopes. Implementations *should* include
    /// `extra_params` in the URI as additional query parameters.
    fn authorization_uri(
        &self,
        config: &OAuthConfig,
        state: &str,
        scopes: &[&str],
        extra_params: &[(&str, &str)],
    ) -> Result<Absolute<'static>, Error>;

    /// Perform the token exchange in accordance with RFC 6749 §4.1.3 given the
    /// authorization code provided by the service.
    fn exchange_code(
        &self,
        config: &OAuthConfig,
        token: TokenRequest,
    ) -> Result<TokenResponse<()>, Error>;
}

struct Shared<K> {
    adapter: Box<dyn Adapter>,
    config: OAuthConfig,
    _k: PhantomData<fn() -> TokenResponse<K>>,
}

/// Utilities for OAuth authentication in Rocket applications.
pub struct OAuth2<K>(Arc<Shared<K>>);

impl<K: 'static> OAuth2<K> {
    /// Create an OAuth2 fairing. The fairing will read the configuration in
    /// `config_name` and register itself in the application so that
    /// `TokenResponse<K>` can be used.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rocket::fairing::AdHoc;
    /// use rocket_oauth2::{HyperSyncRustlsAdapter, OAuth2, OAuthConfig};
    ///
    /// struct GitHub;
    ///
    /// fn main() {
    ///     rocket::ignite()
    ///         .attach(OAuth2::<GitHub>::fairing("github"))
    ///         .launch();
    /// }
    #[cfg(feature = "hyper_sync_rustls_adapter")]
    pub fn fairing(config_name: &str) -> impl Fairing {
        // Unfortunate allocations, but necessary because on_attach requires 'static
        let config_name = config_name.to_string();

        AdHoc::on_attach("OAuth Init", move |rocket| {
            let config = match OAuthConfig::from_config(rocket.config(), &config_name) {
                Ok(c) => c,
                Err(e) => {
                    log::error!("Invalid configuration: {:?}", e);
                    return Err(rocket);
                }
            };

            Ok(rocket.attach(Self::custom(
                hyper_sync_rustls_adapter::HyperSyncRustlsAdapter::default(),
                config,
            )))
        })
    }

    /// Create an OAuth2 fairing with a custom adapter and configuration.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rocket::fairing::AdHoc;
    /// use rocket_oauth2::{HyperSyncRustlsAdapter, OAuth2, OAuthConfig, StaticProvider};
    ///
    /// struct MyProvider;
    ///
    /// fn main() {
    ///     rocket::ignite()
    ///         .attach(AdHoc::on_attach("OAuth Config", |rocket| {
    ///             let config = OAuthConfig::new(
    ///                 StaticProvider {
    ///                     auth_uri: "auth uri".into(),
    ///                     token_uri: "token uri".into(),
    ///                 },
    ///                 "client id".to_string(),
    ///                 "client secret".to_string(),
    ///                 Some("http://localhost:8000/auth".to_string()),
    ///             );
    ///             Ok(rocket.attach(OAuth2::<MyProvider>::custom(HyperSyncRustlsAdapter::default(), config)))
    ///         }))
    ///         .launch();
    /// }
    pub fn custom<A: Adapter>(adapter: A, config: OAuthConfig) -> impl Fairing {
        let shared = Shared::<K> {
            adapter: Box::new(adapter),
            config,
            _k: PhantomData,
        };

        AdHoc::on_attach("OAuth Mount", |rocket| Ok(rocket.manage(Arc::new(shared))))
    }

    /// Prepare an authentication redirect. This sets a state cookie and returns
    /// a `Redirect` to the authorization endpoint.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket::http::Cookies;
    /// use rocket::response::Redirect;
    /// use rocket_oauth2::OAuth2;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/login/github")]
    /// fn github_login(oauth2: OAuth2<GitHub>, mut cookies: Cookies<'_>) -> Redirect {
    ///     oauth2.get_redirect(&mut cookies, &["user:read"]).unwrap()
    /// }
    /// ```
    pub fn get_redirect(
        &self,
        cookies: &mut Cookies<'_>,
        scopes: &[&str],
    ) -> Result<Redirect, Error> {
        self.get_redirect_extras(cookies, scopes, &[])
    }

    /// Prepare an authentication redirect. This sets a state cookie and returns
    /// a `Redirect` to the authorization endpoint. Unlike [`get_redirect`],
    /// this method accepts additional query parameters in `extras`; this can be
    /// used to provide or request additional information to or from providers.
    ///
    /// [`get_redirect`]: Self::get_redirect
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket::http::Cookies;
    /// use rocket::response::Redirect;
    /// use rocket_oauth2::OAuth2;
    ///
    /// struct Reddit;
    ///
    /// #[rocket::get("/login/reddit")]
    /// fn reddit_login(oauth2: OAuth2<Reddit>, mut cookies: Cookies<'_>) -> Redirect {
    ///     oauth2.get_redirect_extras(&mut cookies, &["identity"], &[("duration", "permanent")]).unwrap()
    /// }
    /// ```
    pub fn get_redirect_extras(
        &self,
        cookies: &mut Cookies<'_>,
        scopes: &[&str],
        extras: &[(&str, &str)],
    ) -> Result<Redirect, Error> {
        let state = generate_state(&mut rand::thread_rng())?;
        let uri = self
            .0
            .adapter
            .authorization_uri(&self.0.config, &state, scopes, extras)?;
        cookies.add_private(
            Cookie::build(STATE_COOKIE_NAME, state)
                .same_site(SameSite::Lax)
                .finish(),
        );
        Ok(Redirect::to(uri))
    }

    /// Request a new access token given a refresh token. The refresh token
    /// must have been returned by the provider in a previous [`TokenResponse`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # #![feature(decl_macro)]
    /// use rocket_oauth2::OAuth2;
    ///
    /// struct GitHub;
    ///
    /// #[rocket::get("/")]
    /// fn index(oauth2: OAuth2<GitHub>) {
    ///     // get previously stored refresh_token
    ///     # let refresh_token = "";
    ///     oauth2.refresh(refresh_token).unwrap();
    /// }
    /// ```
    pub fn refresh(&self, refresh_token: &str) -> Result<TokenResponse<K>, Error> {
        self.0
            .adapter
            .exchange_code(
                &self.0.config,
                TokenRequest::RefreshToken(refresh_token.to_string()),
            )
            .map(TokenResponse::cast)
    }
}

impl<'a, 'r, K: 'static> FromRequest<'a, 'r> for OAuth2<K> {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        Outcome::Success(OAuth2(
            request
                .guard::<State<Arc<Shared<K>>>>()
                .expect("OAuth2 fairing was not attached for this key type!")
                .clone(),
        ))
    }
}

impl<C: fmt::Debug> fmt::Debug for OAuth2<C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("OAuth2")
            .field("adapter", &(..))
            .field("config", &self.0.config)
            .finish()
    }
}