http-rs / surf

Fast and friendly HTTP client framework for async Rust
https://docs.rs/surf
Apache License 2.0
1.46k stars 120 forks source link

Need 'curl -u <user:pass>...' functionality #180

Closed jwmurray closed 4 years ago

jwmurray commented 4 years ago

I do not see any options to pass in basic authentication, similar to curl -u url ... -X POST

Is there a method to pass a user:password into the post call?

Thank you.

mainrs commented 4 years ago

Isn't that just a header value? Base64 encode user:pass and set the header Authorization to Basic <base64-value>, without the <>.

Resource

jwmurray commented 4 years ago

Sir Windfield, I appreciate your answer. I have tried for several hours to make this work. I am sure I am just not building the Authorization field with the correct parameters. I will try again this weekend or put a clearer question up on stackoverflow.

jwmurray commented 4 years ago

Thank you for your help.

peterhuene commented 4 years ago

While manually putting the Authorization header together isn't a giant hurdle, it would be nice if surf implemented some auth utility methods, similar to basic_auth and bearer_auth from reqwest.

mainrs commented 4 years ago

Not sure if that is already a thing, but I think stuff like this definitely fits better into the http_types crate. @peterhuene

I'd be happy to help out on this, maybe some utility functions that accept a username and password and generate the right bearer string would be a good starting point. The header name is already inside the crate, available as a const.

makarchuk commented 3 years ago

I've implemented it via Middleware and it works like a charm

pub struct BasicAuth;

#[surf::utils::async_trait]
impl surf::middleware::Middleware for BasicAuth {
    async fn handle(
        &self,
        mut req: surf::Request,
        client: surf::Client,
        next: surf::middleware::Next<'_>,
    ) -> Result<surf::Response, http_types::Error> {
        if let Some(password) = req.url().password() {
            let header_value = format!(
                "Basic {}",
                base64::encode(
                    format!("{}:{}", req.url().username(), password),
                )
            );
            req.set_header("Authorization", header_value);
        }
        next.run(req, client).await
    }
}
AlbanMinassian commented 1 year ago

https://crates.io/crates/http-auth-basic