Add AccessToken::to_bearer_header method
This commit is contained in:
parent
83704cb5ba
commit
ceee4c7e21
20
src/lib.rs
20
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
|
//! ## Persisting tokens
|
||||||
//!
|
//!
|
||||||
//! `TokenPair` implements `Encodable` and `Decodable` from `rustc_serialize`, so can be persisted
|
//! `TokenPair` implements `Encodable` and `Decodable` from `rustc_serialize`, so can be persisted
|
||||||
|
|
12
src/token.rs
12
src/token.rs
|
@ -1,6 +1,7 @@
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
use chrono::{DateTime, UTC, TimeZone};
|
use chrono::{DateTime, UTC, TimeZone};
|
||||||
|
use hyper::header;
|
||||||
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
|
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
|
||||||
|
|
||||||
/// OAuth 2.0 access token and refresh token pair.
|
/// OAuth 2.0 access token and refresh token pair.
|
||||||
|
@ -58,6 +59,17 @@ impl AccessToken {
|
||||||
pub fn expired(&self) -> bool {
|
pub fn expired(&self) -> bool {
|
||||||
self.expires.map_or(false, |dt| dt < UTC::now())
|
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<header::Authorization<header::Bearer>> {
|
||||||
|
if self.token_type == AccessTokenType::Bearer {
|
||||||
|
Some(header::Authorization(header::Bearer { token: self.token.clone() }))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Deref for TokenPair {
|
impl Deref for TokenPair {
|
||||||
|
|
Loading…
Reference in New Issue