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

Adds a simple bearer token authorization wrapper for a client #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
32 changes: 32 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,35 @@ pub trait Client: Sync + Send {
Ok(response)
}
}

/// Client that wraps another client and adds a bearer token authentication header to each request.
pub struct BearerTokenAuthClient<C: Client> {
token: String,
client: C,
}

impl <C: Client> BearerTokenAuthClient<C> {
/// Construct from an arbitrary client and a bearer token.
pub fn new(client: C, token: &str) -> Self {
Self { client, token: token.to_string() }
}
}

#[async_trait::async_trait]
impl <C: Client> Client for BearerTokenAuthClient<C> {
fn base(&self) -> &str {
self.client.base()
}

async fn send(&self, mut req: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, ClientError> {
let bearer = format!("Bearer {}", self.token);
match http::HeaderValue::from_str(&bearer) {
Ok(mut bearer) => {
bearer.set_sensitive(true);
req.headers_mut().insert("Authorization", bearer);
self.client.send(req).await
}
Err(e) => Err(ClientError::GenericError { source: e.into() })
}
}
}
9 changes: 8 additions & 1 deletion src/clients/reqwest.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Contains an implementation of [Client][crate::client::Client] being backed
//! by the [reqwest](https://docs.rs/reqwest/) crate.

use crate::{client::Client as RustifyClient, errors::ClientError};
use crate::{client::{Client as RustifyClient, BearerTokenAuthClient}, errors::ClientError};
use async_trait::async_trait;
use http::{Request, Response};
use std::convert::TryFrom;
Expand Down Expand Up @@ -102,3 +102,10 @@ impl RustifyClient for Client {
.map_err(|e| ClientError::ResponseError { source: e.into() })
}
}

impl BearerTokenAuthClient<Client> {
/// Construct from a default client using a given base URL and a bearer token.
pub fn default(base: &str, token: &str) -> Self {
BearerTokenAuthClient::new(Client::default(base), token)
}
}
21 changes: 20 additions & 1 deletion tests/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::fmt::Debug;
use common::{Middle, TestGenericWrapper, TestResponse, TestServer};
use derive_builder::Builder;
use httpmock::prelude::*;
use rustify::endpoint::Endpoint;
use rustify::{client::BearerTokenAuthClient, endpoint::Endpoint};
use rustify_derive::Endpoint;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
Expand Down Expand Up @@ -349,3 +349,22 @@ async fn test_complex() {
assert!(r.is_ok());
assert_eq!(r.unwrap().parse().unwrap().age, 30);
}

#[test(tokio::test)]
async fn test_bearer_token_auth_client() {
#[derive(Endpoint)]
#[endpoint(path = "test/path")]
struct Test {}

let t = TestServer::default();
let e = Test {};
let m = t.server.mock(|when, then| {
when.header("Authorization", "Bearer 1234567890");
then.status(200);
});
let client = BearerTokenAuthClient::new(t.client, "1234567890");
let r = e.exec(&client).await;

m.assert();
assert!(r.is_ok());
}