stubr/model/request/auth/
helpers.rs

1use crate::wiremock::Request;
2use jsonwebtoken::Header;
3use serde_json::Value;
4
5use super::{AUTHORIZATION_HEADER, BEARER_PREFIX};
6
7pub trait RequestAuthExtension {
8    fn authorization_header(&self) -> Option<&str>;
9
10    fn jwt(&self) -> Option<&str> {
11        self.authorization_header()
12            .filter(|h| h.contains(BEARER_PREFIX))
13            .map(|h| &h[BEARER_PREFIX.len() + 1..])
14    }
15
16    fn jwt_header(&self) -> Option<Header> {
17        self.jwt().and_then(|jwt| jsonwebtoken::decode_header(jwt).ok())
18    }
19
20    fn jwt_payload(&self) -> Option<Value> {
21        use base64::Engine as _;
22        self.jwt().and_then(|jwt| {
23            jwt.split('.')
24                .take(2)
25                .last()
26                .and_then(|payload| base64::prelude::BASE64_STANDARD.decode(payload).ok())
27                .and_then(|payload| serde_json::from_slice(payload.as_slice()).ok())
28        })
29    }
30}
31
32impl RequestAuthExtension for Request {
33    fn authorization_header(&self) -> Option<&str> {
34        self.headers.get(&AUTHORIZATION_HEADER).map(|v| v.as_str())
35    }
36}