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

Doc: how to request S3 compatible API with signature #1

Open
foreseaz opened this issue Mar 19, 2023 · 1 comment
Open

Doc: how to request S3 compatible API with signature #1

foreseaz opened this issue Mar 19, 2023 · 1 comment
Assignees

Comments

@foreseaz
Copy link
Owner

https://gist.github.com/foreseaz/0da077d6f2b2ac75cfc23946be2c470d

@foreseaz foreseaz changed the title Doc: how request S3 compatible API with signature Doc: how to request S3 compatible API with signature Mar 19, 2023
@foreseaz
Copy link
Owner Author

use sha2::{Sha256, Digest};

const S3_ACCESS: &str = "ACCESS";
const S3_SECRET: &str = "SECRET";

fn sha256_string(input: String) -> String {
    let mut hasher = Sha256::new();
    hasher.update(input);
    let result = hasher.finalize();
    format!("{:x}", result)
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let datetime = chrono::Utc::now();
    let host = "{ACCOUNT_ID}.r2.cloudflarestorage.com";
    let url = format!("https://{}", host);
    let mut headers = reqwest::header::HeaderMap::new();

    headers.insert(
        "X-Amz-Date",
        datetime
            .format("%Y%m%dT%H%M%SZ")
            .to_string()
            .parse()
            .unwrap(),
    );
    headers.insert("host", host.parse().unwrap());
    let payload = "".to_string();
    let hashed_payload = sha256_string(payload);
    headers.insert("x-amz-content-sha256", hashed_payload.parse().unwrap());

    let s = aws_sign_v4::AwsSign::new(
        "GET",
        &url,
        &datetime,
        &headers,
        "auto",
        &S3_ACCESS,
        &S3_SECRET,
        "s3",
        ""
    );
    let signature = s.sign();
    println!("{:#?}", signature);
    headers.insert(reqwest::header::AUTHORIZATION, signature.parse().unwrap());

    let client = reqwest::Client::new();
    let res = client
        .get(url)
        .headers(headers.to_owned())
        .body("")
        .send()
        .await?;

    println!("Status: {}", res.status());
    let body = res.text().await?;
    println!("Body:\n\n{}", body);
    Ok(())
}

Rust version is simpler with aws_sign_v4

@foreseaz foreseaz self-assigned this Mar 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant