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 basic_auth() & bearer_auth() on ClientBuilder #1398

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
59 changes: 58 additions & 1 deletion src/async_impl/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ use std::time::Duration;
use std::{collections::HashMap, convert::TryInto, net::SocketAddr};
use std::{fmt, str};

use base64::encode;
use bytes::Bytes;
use http::header::{
Entry, HeaderMap, HeaderValue, ACCEPT, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH,
CONTENT_TYPE, LOCATION, PROXY_AUTHORIZATION, RANGE, REFERER, TRANSFER_ENCODING, USER_AGENT,
CONTENT_TYPE, LOCATION, PROXY_AUTHORIZATION, RANGE, REFERER, TRANSFER_ENCODING, USER_AGENT, AUTHORIZATION,
};
use http::uri::Scheme;
use http::Uri;
Expand Down Expand Up @@ -881,6 +882,62 @@ impl ClientBuilder {
self
}

/// Enable HTTP basic authentication.
///
/// ```rust
/// # use reqwest::Error;
/// # async fn run() -> Result<(), Error> {
/// let client = reqwest::ClientBuilder::new()
/// .basic_auth("admin", Some("good password"))
/// .build()?;
/// let resp = client.delete("http://httpbin.org/delete")
/// .send()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn basic_auth<U, P>(mut self, username: U, password: Option<P>) -> ClientBuilder
where
U: fmt::Display,
P: fmt::Display,
{
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}:", username),
};
cocool97 marked this conversation as resolved.
Show resolved Hide resolved
let header_value = format!("Basic {}", encode(&auth));

match header_value.try_into() {
Ok(header_value) => {
self.config.headers.insert(AUTHORIZATION, header_value);
}
Err(e) => {
self.config.error = Some(crate::error::builder::<http::Error>(e.into()));
}
};

self
}

/// Enable HTTP bearer authentication.
pub fn bearer_auth<T>(mut self, token: T) -> ClientBuilder
where
T: fmt::Display,
{
let header_value = format!("Bearer {}", token);

match header_value.try_into() {
Ok(header_value) => {
self.config.headers.insert(AUTHORIZATION, header_value);
}
Err(e) => {
self.config.error = Some(crate::error::builder::<http::Error>(e.into()));
}
};

self
}

/// Enable a persistent cookie store for the client.
///
/// Cookies received in responses will be preserved and included in
Expand Down
30 changes: 30 additions & 0 deletions src/blocking/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,36 @@ impl ClientBuilder {
self.with_inner(move |inner| inner.default_headers(headers))
}

/// Enable HTTP basic authentication.
///
/// ```rust
/// # use reqwest::Error;
/// # async fn run() -> Result<(), Error> {
/// let client = reqwest::blocking::ClientBuilder::new()
/// .basic_auth("admin", Some("good password"))
/// .build()?;
/// let resp = client.delete("http://httpbin.org/delete")
/// .send()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn basic_auth<U, P>(self, username: U, password: Option<P>) -> ClientBuilder
where
U: fmt::Display,
P: fmt::Display,
{
self.with_inner(move |inner| inner.basic_auth(username, password))
}

/// Enable HTTP bearer authentication.
pub fn bearer_auth<T>(self, token: T) -> ClientBuilder
where
T: fmt::Display,
{
self.with_inner(move |inner| inner.bearer_auth(token))
}

/// Enable a persistent cookie store for the client.
///
/// Cookies received in responses will be preserved and included in
Expand Down
48 changes: 48 additions & 0 deletions tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,54 @@ async fn user_agent() {
assert_eq!(res.status(), reqwest::StatusCode::OK);
}

#[tokio::test]
async fn basic_auth() {
let server = server::http(move |req| async move {
assert_eq!(
req.headers()["authorization"],
"Basic YWRtaW46Z29vZCBwYXNzd29yZA=="
);
http::Response::default()
});

let url = format!("http://{}/basic", server.addr());
let res = reqwest::Client::builder()
.basic_auth("admin", Some("good password"))
.build()
.expect("client builder")
.get(&url)
.send()
.await
.expect("request");

assert_eq!(res.status(), reqwest::StatusCode::OK);
}

#[tokio::test]
async fn bearer_auth() {
let bearer_token = "iwefOJASndcsde645f";

let server = server::http(move |req| async move {
assert_eq!(
req.headers()["authorization"],
format!("Bearer {}", bearer_token)
);
http::Response::default()
});

let url = format!("http://{}/basic", server.addr());
let res = reqwest::Client::builder()
.bearer_auth(bearer_token)
.build()
.expect("client builder")
.get(&url)
.send()
.await
.expect("request");

assert_eq!(res.status(), reqwest::StatusCode::OK);
}

#[tokio::test]
async fn response_text() {
let _ = env_logger::try_init();
Expand Down