Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BearerTokenCredentialPolicy to azure_core #1726

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions sdk/core/azure_core/src/policies/bearer_token_policy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use crate::{
auth::TokenCredential,
headers::AUTHORIZATION,
policies::{Policy, PolicyResult},
Context, Request,
};
use async_trait::async_trait;
use std::sync::Arc;

#[derive(Debug, Clone)]
pub struct BearerTokenCredentialPolicy {
credential: Arc<dyn TokenCredential>,
scopes: Vec<String>,
}

impl BearerTokenCredentialPolicy {
pub fn new<A, B>(credential: Arc<dyn TokenCredential>, scopes: A) -> Self
where
A: IntoIterator<Item = B>,
B: Into<String>,
{
Self {
credential,
scopes: scopes.into_iter().map(|s| s.into()).collect(),
}
}
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Policy for BearerTokenCredentialPolicy {
async fn send(
&self,
ctx: &Context,
request: &mut Request,
next: &[Arc<dyn Policy>],
) -> PolicyResult {
let scopes = self
.scopes
.iter()
.map(|s| s.as_str())
.collect::<Vec<&str>>();
let access_token = self.credential.get_token(&scopes).await?;
vincenttran-msft marked this conversation as resolved.
Show resolved Hide resolved
let token = access_token.token.secret();

request.insert_header(AUTHORIZATION, format!("Bearer {token}"));

next[0].send(ctx, request, &next[1..]).await
}
}
2 changes: 2 additions & 0 deletions sdk/core/azure_core/src/policies/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
mod bearer_token_policy;
mod custom_headers_policy;
mod retry_policies;
mod telemetry_policy;
mod transport;

pub use bearer_token_policy::BearerTokenCredentialPolicy;
pub use custom_headers_policy::{CustomHeaders, CustomHeadersPolicy};
pub use retry_policies::*;
pub use telemetry_policy::*;
Expand Down