diff --git a/src/lib.rs b/src/lib.rs index 5098fab..333999c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -89,6 +89,26 @@ //! } //! ``` //! +//! ## Using bearer access tokens +//! +//! If the obtained token is of the `Bearer` type, a Hyper `Authorization` header can be created +//! from it. +//! +//! ```no_run +//! # extern crate hyper; +//! # extern crate inth_oauth2; +//! # fn main() { +//! # use inth_oauth2::Client as OAuth2; +//! # let auth = OAuth2::google(Default::default(), "", "", None); +//! # let token_pair = auth.request_token("").unwrap(); +//! let client = hyper::Client::new(); +//! let res = client.get("https://example.com/resource") +//! .header(token_pair.to_bearer_header().unwrap()) +//! .send() +//! .unwrap(); +//! # } +//! ``` +//! //! ## Persisting tokens //! //! `TokenPair` implements `Encodable` and `Decodable` from `rustc_serialize`, so can be persisted diff --git a/src/token.rs b/src/token.rs index e9296f6..9cca8f3 100644 --- a/src/token.rs +++ b/src/token.rs @@ -1,6 +1,7 @@ use std::ops::Deref; use chrono::{DateTime, UTC, TimeZone}; +use hyper::header; use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; /// OAuth 2.0 access token and refresh token pair. @@ -58,6 +59,17 @@ impl AccessToken { pub fn expired(&self) -> bool { self.expires.map_or(false, |dt| dt < UTC::now()) } + + /// Creates an Authorization header. + /// + /// Returns `None` if `token_type` is not `Bearer`. + pub fn to_bearer_header(&self) -> Option> { + if self.token_type == AccessTokenType::Bearer { + Some(header::Authorization(header::Bearer { token: self.token.clone() })) + } else { + None + } + } } impl Deref for TokenPair {