From ceca96da281ec0b7d3bdce202f1eb84d2447ce15 Mon Sep 17 00:00:00 2001 From: Stephen Ellis Date: Wed, 6 Mar 2019 01:56:12 -0800 Subject: [PATCH] Added HTTP Authentication for Client (#540) --- CHANGES.md | 2 ++ src/client/request.rs | 24 ++++++++++++++++++++++++ tests/test_client.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 1a326028..8cce7159 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,6 +8,8 @@ * Add `insert` and `remove` methods to `HttpResponseBuilder` +* Add client HTTP Authentication methods `.basic_auth()` and `.bearer_auth()`. #540 + ### Fixed * Ignored the `If-Modified-Since` if `If-None-Match` is specified. #680 diff --git a/src/client/request.rs b/src/client/request.rs index ad08ad13..89789933 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -12,6 +12,7 @@ use serde::Serialize; use serde_json; use serde_urlencoded; use url::Url; +use base64::encode; use super::connector::{ClientConnector, Connection}; use super::pipeline::SendRequest; @@ -485,6 +486,29 @@ impl ClientRequestBuilder { self } + /// Set HTTP basic authorization + pub fn basic_auth(&mut self, username: U, password: Option

) -> &mut Self + where + U: fmt::Display, + P: fmt::Display, + { + let auth = match password { + Some(password) => format!("{}:{}", username, password), + None => format!("{}", username) + }; + let header_value = format!("Basic {}", encode(&auth)); + self.header(header::AUTHORIZATION, &*header_value) + } + + /// Set HTTP bearer authentication + pub fn bearer_auth( &mut self, token: T) -> &mut Self + where + T: fmt::Display, + { + let header_value = format!("Bearer {}", token); + self.header(header::AUTHORIZATION, &*header_value) + } + /// Set content length #[inline] pub fn content_length(&mut self, len: u64) -> &mut Self { diff --git a/tests/test_client.rs b/tests/test_client.rs index 9808f3e6..f3151e3a 100644 --- a/tests/test_client.rs +++ b/tests/test_client.rs @@ -506,3 +506,31 @@ fn client_read_until_eof() { let bytes = sys.block_on(response.body()).unwrap(); assert_eq!(bytes, Bytes::from_static(b"welcome!")); } + +#[test] +fn client_basic_auth() { + let mut srv = + test::TestServer::new(|app| app.handler(|_| HttpResponse::Ok().body(STR))); + /// set authorization header to Basic + let request = srv + .get() + .basic_auth("username", Some("password")) + .finish() + .unwrap(); + let repr = format!("{:?}", request); + assert!(repr.contains("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")); +} + +#[test] +fn client_bearer_auth() { + let mut srv = + test::TestServer::new(|app| app.handler(|_| HttpResponse::Ok().body(STR))); + /// set authorization header to Bearer + let request = srv + .get() + .bearer_auth("someS3cr3tAutht0k3n") + .finish() + .unwrap(); + let repr = format!("{:?}", request); + assert!(repr.contains("Bearer someS3cr3tAutht0k3n")); +} \ No newline at end of file