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
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct DecodedIdToken {
pub aud: String,
pub auth_time: usize,
pub exp: usize,
pub iat: usize,
pub iss: String,
pub sub: String,
}
pub async fn verify_id_token_with_project_id(
token: &str,
project_id: &str,
) -> Result<DecodedIdToken, Box<dyn std::error::Error>> {
let header = match jsonwebtoken::decode_header(token) {
Ok(output) => output,
Err(_) => return Err(std::boxed::Box::from(String::from("Header"))),
};
if header.alg != jsonwebtoken::Algorithm::RS256 {
return Err(std::boxed::Box::from(String::from("Algorithm")));
}
let kid = match header.kid {
Some(value) => value,
None => return Err(std::boxed::Box::from(String::from("Kid"))),
};
let public_keys = reqwest::get(
"https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com",
)
.await?
.json::<std::collections::HashMap<String, String>>()
.await?;
if !public_keys.contains_key(&kid) {
return Err(std::boxed::Box::from(String::from("Public Keys Kid")));
}
let public_key = match public_keys.get(&kid) {
Some(value) => value,
None => return Err(std::boxed::Box::from(String::from("Public Key"))),
};
let decoded_id_token = match jsonwebtoken::dangerous_unsafe_decode::<DecodedIdToken>(&token) {
Ok(value) => value.claims,
Err(error) => return Err(std::boxed::Box::from(format!("{:?}", error))),
};
Ok(decoded_id_token)
}