elastic-rs / elastic

An Elasticsearch REST API client for Rust
Apache License 2.0
252 stars 40 forks source link

Basic auth example #363

Closed MikhailMS closed 5 years ago

MikhailMS commented 5 years ago

Hello there,

It would be interesting to see how I can pass authenticaiton credentials when using this library. Since there is no example anywhere and docs aren't clear on that matter, I'd like to ask this in the issue, which is not the best way (I think), but see no another option.

I've tried a couple of options with headers

  1. setting it directly to SyncClientBuilder
  2. setting it to reqwest ClientBuilder and then passing reqwest client to SyncClientBuilder but neither was successful

Solution to the issue then may ideally lead to an example file in the repo :)

dcarosone commented 5 years ago

FWIW, here's an example, not necessarily the best example

let client = SyncClientBuilder::new()
    .static_node("https://es.example.com:9200")
    .params_fluent(|p| {
        p.header(
            AUTHORIZATION,
            HeaderValue::from_str(&format!(
                "Basic {}",
                encode(r#"username:password"#)
            ))
           .unwrap(),
        )
    })
    .build()
    .unwrap();
KodrAus commented 5 years ago

Thanks for the example @dcarosone! We could definitely wrap that up more nicely in the client so you don't have to fiddle with http headers yourself.

mwilliammyers commented 5 years ago

Closing in favor of #400 which has more info.

mwilliammyers commented 5 years ago

As of: #401 (6ed243570bb64fdf398cafe0518c5d9a02321c76) you can now do:

use elastic::client::SyncClientBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let http_client = reqwest::Client::builder()
        .danger_accept_invalid_certs(true)
        .build()?;

    let client = SyncClientBuilder::new()
        .static_node("https://localhost:9201")
        .http_client(http_client)
        .params_fluent(|p| p.basic_auth("admin", Some("admin")).unwrap())
        .build()?;

    println!("{:#?}", client.ping().send()?);

    Ok(())
}