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
use crate::idtoken::IdToken;
use crate::jwt::{Claim, JsonWebToken, JwtParser};
use chrono::{DateTime, Duration, TimeZone, Utc};
use chrono_humanize::HumanTime;
use from_as::*;
use graph_error::{GraphFailure, WithGraphError, WithGraphErrorAsync};
use serde_aux::prelude::*;
use std::convert::TryFrom;
use std::fmt;
use std::io::{Read, Write};
/// OAuth 2.0 Access Token
///
/// Create a new AccessToken.
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
/// let access_token = AccessToken::new("Bearer", 3600, "Read Read.Write", "ASODFIUJ34KJ;LADSK");
/// ```
///
/// You can also get the claims using the claims() method as well as
/// the remaining duration that the access token is valid using the elapsed()
/// method.
///
/// Tokens returned for personal microsoft accounts that use legacy MSA
/// are encrypted and cannot be parsed. This bearer token may still be
/// valid but the jwt() method will return None.
/// For more info see:
/// [Microsoft identity platform acccess tokens](https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens)
///
///
/// For tokens where the JWT can be parsed the elapsed() method uses
/// the `exp` field in the JWT's claims. If the claims do not contain an
/// `exp` field or the token could not be parsed the elapsed() method
/// uses the expires_in field returned in the response body to caculate
/// the remaining time. These fields are only used once during
/// initialization to set a timestamp for future expiration of the access
/// token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
/// # let access_token = AccessToken::new("Bearer", 3600, "Read Read.Write", "ASODFIUJ34KJ;LADSK");
///
/// // Claims
/// println!("{:#?}", access_token.claims());
///
/// // Duration left until expired.
/// println!("{:#?}", access_token.elapsed());
/// ```
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AccessToken {
access_token: String,
token_type: String,
#[serde(deserialize_with = "deserialize_number_from_string")]
expires_in: i64,
scope: Option<String>,
refresh_token: Option<String>,
user_id: Option<String>,
id_token: Option<String>,
state: Option<String>,
timestamp: Option<DateTime<Utc>>,
#[serde(skip)]
jwt: Option<JsonWebToken>,
}
impl AccessToken {
pub fn new(token_type: &str, expires_in: i64, scope: &str, access_token: &str) -> AccessToken {
let mut token = AccessToken {
token_type: token_type.into(),
expires_in,
scope: Some(scope.into()),
access_token: access_token.into(),
refresh_token: None,
user_id: None,
id_token: None,
state: None,
timestamp: Some(Utc::now() + Duration::seconds(expires_in)),
jwt: None,
};
token.parse_jwt();
token
}
/// Set the token type.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_token_type("Bearer");
/// ```
pub fn set_token_type(&mut self, s: &str) -> &mut AccessToken {
self.token_type = s.into();
self
}
/// Set the expies in time. This should usually be done in seconds.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_expires_in(3600);
/// ```
pub fn set_expires_in(&mut self, expires_in: i64) -> &mut AccessToken {
self.expires_in = expires_in;
self.timestamp = Some(Utc::now() + Duration::seconds(expires_in));
self
}
/// Set the scope.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_scope("Read Read.Write");
/// ```
pub fn set_scope(&mut self, s: &str) -> &mut AccessToken {
self.scope = Some(s.to_string());
self
}
/// Set the access token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_bearer_token("ASODFIUJ34KJ;LADSK");
/// ```
pub fn set_bearer_token(&mut self, s: &str) -> &mut AccessToken {
self.access_token = s.into();
self
}
/// Set the refresh token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_refresh_token("#ASOD323U5342");
/// ```
pub fn set_refresh_token(&mut self, s: &str) -> &mut AccessToken {
self.refresh_token = Some(s.to_string());
self
}
/// Set the user id.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_user_id("user_id");
/// ```
pub fn set_user_id(&mut self, s: &str) -> &mut AccessToken {
self.user_id = Some(s.to_string());
self
}
/// Set the id token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::{AccessToken, IdToken};
///
/// let mut access_token = AccessToken::default();
/// access_token.set_id_token("id_token");
/// ```
pub fn set_id_token(&mut self, s: &str) -> &mut AccessToken {
self.id_token = Some(s.to_string());
self
}
/// Set the id token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::{AccessToken, IdToken};
///
/// let mut access_token = AccessToken::default();
/// access_token.with_id_token(IdToken::new("id_token", "code", "state", "session_state"));
/// ```
pub fn with_id_token(&mut self, id_token: IdToken) {
self.id_token = Some(id_token.get_id_token());
}
/// Set the state.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
/// # use graph_oauth::oauth::IdToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.set_state("state");
/// ```
pub fn set_state(&mut self, s: &str) -> &mut AccessToken {
self.state = Some(s.to_string());
self
}
/// Reset the access token timestmap.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// access_token.timestamp();
/// // The timestamp is in UTC.
/// ```
pub fn gen_timestamp(&mut self) {
self.timestamp = Some(Utc::now() + Duration::seconds(self.expires_in));
}
/// Get the token type.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.token_type());
/// ```
pub fn token_type(&self) -> &str {
self.token_type.as_str()
}
/// Set the user id.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// // This is the original amount that was set not the difference.
/// // To get the difference you can use access_token.elapsed().
/// println!("{:#?}", access_token.expires_in());
/// ```
pub fn expires_in(&self) -> i64 {
self.expires_in
}
/// Get the scopes.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.scopes());
/// ```
pub fn scopes(&self) -> Option<&String> {
self.scope.as_ref()
}
/// Get the access token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.bearer_token());
/// ```
pub fn bearer_token(&self) -> &str {
self.access_token.as_str()
}
/// Get the user id.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.user_id());
/// ```
pub fn user_id(&self) -> Option<String> {
self.user_id.clone()
}
/// Get the refresh token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.refresh_token());
/// ```
pub fn refresh_token(&self) -> Option<String> {
self.refresh_token.clone()
}
/// Get the id token.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.id_token());
/// ```
pub fn id_token(&self) -> Option<String> {
self.id_token.clone()
}
/// Get the state.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.state());
/// ```
pub fn state(&self) -> Option<String> {
self.state.clone()
}
/// Get the timestamp.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.timestamp());
/// ```
pub fn timestamp(&self) -> Option<DateTime<Utc>> {
self.timestamp
}
// TODO: This should checked using the bearer token.
/// Check whether the access token is expired. An access token is considerd
/// expired when there is a negative difference between the timestamp set
/// for the access token and the expires_in field.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.is_expired());
/// ```
pub fn is_expired(&self) -> bool {
if let Some(human_time) = self.elapsed() {
return human_time.le(&HumanTime::from(Duration::seconds(0)));
}
true
}
// TODO: This should checked using the bearer token.
/// Get the time left in seconds until the access token expires.
/// See the HumanTime crate. If you just need to know if the access token
/// is expired then use the is_expired() message which returns a boolean
/// true for the token has expired and false otherwise.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::AccessToken;
///
/// let mut access_token = AccessToken::default();
/// println!("{:#?}", access_token.elapsed());
/// ```
pub fn elapsed(&self) -> Option<HumanTime> {
if let Some(timestamp) = self.timestamp {
let ht = HumanTime::from(timestamp);
return Some(ht);
}
None
}
fn parse_jwt(&mut self) {
let mut set_timestamp = false;
if let Ok(jwt) = JwtParser::parse(self.bearer_token()) {
if let Some(claims) = jwt.claims() {
if let Some(claim) = claims
.iter()
.find(|item| item.key().eq(&String::from("exp")))
{
let value = claim.value();
let number = value.as_i64().unwrap();
self.timestamp = Some(Utc.timestamp(number, 0));
set_timestamp = true;
}
}
self.jwt = Some(jwt);
}
if !set_timestamp {
self.gen_timestamp();
}
}
pub fn claims(&self) -> Option<Vec<Claim>> {
self.jwt.as_ref()?.claims()
}
pub fn jwt(&self) -> Option<&JsonWebToken> {
self.jwt.as_ref()
}
pub(crate) async fn try_from_async(
builder: reqwest::RequestBuilder,
) -> Result<AccessToken, GraphFailure> {
let mut access_token = builder
.send()
.await?
.with_graph_error()
.await?
.json::<AccessToken>()
.await?;
access_token.parse_jwt();
Ok(access_token)
}
}
impl Default for AccessToken {
fn default() -> Self {
AccessToken {
token_type: String::new(),
expires_in: 0,
scope: None,
access_token: String::new(),
refresh_token: None,
user_id: None,
id_token: None,
state: None,
timestamp: Some(Utc::now() + Duration::seconds(0)),
jwt: None,
}
}
}
impl TryFrom<&str> for AccessToken {
type Error = GraphFailure;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut access_token: AccessToken = serde_json::from_str(value)?;
access_token.parse_jwt();
Ok(access_token)
}
}
impl TryFrom<reqwest::blocking::RequestBuilder> for AccessToken {
type Error = GraphFailure;
fn try_from(value: reqwest::blocking::RequestBuilder) -> Result<Self, Self::Error> {
let response = value.send()?;
let access_token: AccessToken = AccessToken::try_from(response)?;
Ok(access_token)
}
}
impl TryFrom<Result<reqwest::blocking::Response, reqwest::Error>> for AccessToken {
type Error = GraphFailure;
fn try_from(
value: Result<reqwest::blocking::Response, reqwest::Error>,
) -> Result<Self, Self::Error> {
let response = value?;
AccessToken::try_from(response)
}
}
impl TryFrom<reqwest::blocking::Response> for AccessToken {
type Error = GraphFailure;
fn try_from(value: reqwest::blocking::Response) -> Result<Self, Self::Error>
where
Self: for<'de> serde::Deserialize<'de>,
{
let mut access_token = value.with_graph_error()?.json::<AccessToken>()?;
access_token.parse_jwt();
Ok(access_token)
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AccessToken")
.field("bearer_token", &"[REDACTED]")
.field("token_type", &self.token_type)
.field("expires_in", &self.expires_in)
.field("scope", &self.scope)
.field("user_id", &self.user_id)
.field("id_token", &"[REDACTED]")
.field("state", &self.state)
.field("timestamp", &self.timestamp)
.finish()
}
}