diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/lib.rs | 10 | ||||
-rw-r--r-- | src/tests.rs | 16 |
2 files changed, 26 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs index 9caedff31914..9374460d2428 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,7 @@ extern crate curl; #[cfg(feature = "json")] extern crate serde; #[cfg(feature = "json")] extern crate serde_json; +#[cfg(feature = "basic_auth")] extern crate base64; use curl::easy::{Easy, Form, List, ReadError}; use std::collections::HashMap; @@ -136,6 +137,15 @@ impl <'a> Request<'a> { Ok(self) } + #[cfg(feature = "basic_auth")] + /// Set the `Authorization` header to a basic authentication value + /// from the supplied username and password. + pub fn basic_auth(mut self, username: &str, password: &str) -> Result<Self, curl::Error> { + let auth = base64::encode(format!("{}:{}", username, password).as_bytes()); + self.headers.append(&format!("Authorization: Basic {}", auth))?; + Ok(self) + } + /// Add a byte-array body to a request using the specified /// `Content-Type`. pub fn body(mut self, content_type: &'a str, data: &'a [u8]) -> Self { diff --git a/src/tests.rs b/src/tests.rs index cc44ca7b53a0..088334aa2784 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -88,3 +88,19 @@ fn test_http_post_json() { "Content-Type should be `application/json`", ); } + +// Tests for different authentication methods that are supported +// out-of-the-box: + +#[cfg(feature = "basic_auth")] #[test] +fn test_basic_auth() { + let request = Request::new( + Method::Get, "https://httpbin.org/basic-auth/alan_watts/oneness" + ); + + let response = request + .basic_auth("alan_watts", "oneness").expect("failed to set auth header") + .send().expect("failed to send request"); + + assert!(response.is_success(), "authorized request should succeed"); +} |