1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00

Added HTTP Authentication for Client (#540)

This commit is contained in:
Stephen Ellis 2019-03-06 01:56:12 -08:00 committed by Douman
parent 42f030d3f4
commit ceca96da28
3 changed files with 54 additions and 0 deletions

View File

@ -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

View File

@ -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<U, P>(&mut self, username: U, password: Option<P>) -> &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<T>( &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 {

View File

@ -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 <base64 encoded username:password>
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 <token>
let request = srv
.get()
.bearer_auth("someS3cr3tAutht0k3n")
.finish()
.unwrap();
let repr = format!("{:?}", request);
assert!(repr.contains("Bearer someS3cr3tAutht0k3n"));
}