Skip to content

Commit 127c336

Browse files
authored
add audience to custom_service_account (#119)
1 parent 9ed8eef commit 127c336

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

src/custom_service_account.rs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ pub struct CustomServiceAccount {
3131
signer: Signer,
3232
tokens: RwLock<HashMap<Vec<String>, Arc<Token>>>,
3333
subject: Option<String>,
34+
audience: Option<String>,
3435
}
3536

3637
impl CustomServiceAccount {
@@ -59,6 +60,12 @@ impl CustomServiceAccount {
5960
self
6061
}
6162

63+
/// Set the `Audience` to impersonate a user
64+
pub fn with_audience(mut self, audience: String) -> Self {
65+
self.audience = Some(audience);
66+
self
67+
}
68+
6269
fn new(credentials: ServiceAccountKey, client: HttpClient) -> Result<Self, Error> {
6370
debug!(project = ?credentials.project_id, email = credentials.client_email, "found credentials");
6471
Ok(Self {
@@ -67,13 +74,19 @@ impl CustomServiceAccount {
6774
credentials,
6875
tokens: RwLock::new(HashMap::new()),
6976
subject: None,
77+
audience: None,
7078
})
7179
}
7280

7381
#[instrument(level = Level::DEBUG, skip(self))]
7482
async fn fetch_token(&self, scopes: &[&str]) -> Result<Arc<Token>, Error> {
75-
let jwt =
76-
Claims::new(&self.credentials, scopes, self.subject.as_deref()).to_jwt(&self.signer)?;
83+
let jwt = Claims::new(
84+
&self.credentials,
85+
scopes,
86+
self.subject.as_deref(),
87+
self.audience.as_deref(),
88+
)
89+
.to_jwt(&self.signer)?;
7790
let body = Bytes::from(
7891
form_urlencoded::Serializer::new(String::new())
7992
.extend_pairs(&[("grant_type", GRANT_TYPE), ("assertion", jwt.as_str())])
@@ -156,7 +169,12 @@ pub(crate) struct Claims<'a> {
156169
}
157170

158171
impl<'a> Claims<'a> {
159-
pub(crate) fn new(key: &'a ServiceAccountKey, scopes: &[&str], sub: Option<&'a str>) -> Self {
172+
pub(crate) fn new(
173+
key: &'a ServiceAccountKey,
174+
scopes: &[&str],
175+
sub: Option<&'a str>,
176+
aud: Option<&'a str>,
177+
) -> Self {
160178
let mut scope = String::with_capacity(16);
161179
for (i, s) in scopes.iter().enumerate() {
162180
if i != 0 {
@@ -169,7 +187,7 @@ impl<'a> Claims<'a> {
169187
let iat = Utc::now().timestamp();
170188
Claims {
171189
iss: &key.client_email,
172-
aud: &key.token_uri,
190+
aud: aud.unwrap_or(&key.token_uri),
173191
exp: iat + 3600 - 5, // Max validity is 1h
174192
iat,
175193
sub,

0 commit comments

Comments
 (0)