Replies: 1 comment
-
|
You can implement request signing/encryption by creating a middleware-style wrapper around your HTTP client. Since Dioxus doesn't have built-in middleware for API calls, the idiomatic approach is: 1. Create a signed HTTP client wrapperuse reqwest::Client;
use hmac::{Hmac, Mac};
use sha2::Sha256;
pub struct SignedClient {
inner: Client,
secret_key: Vec<u8>,
}
impl SignedClient {
pub fn new(secret: &[u8]) -> Self {
Self {
inner: Client::new(),
secret_key: secret.to_vec(),
}
}
pub async fn signed_request(
&self,
url: &str,
body: &[u8],
) -> reqwest::Result<reqwest::Response> {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string();
let mut mac = Hmac::<Sha256>::new_from_slice(&self.secret_key).unwrap();
mac.update(body);
mac.update(timestamp.as_bytes());
let signature = hex::encode(mac.finalize().into_bytes());
self.inner
.post(url)
.header("X-Timestamp", ×tamp)
.header("X-Signature", &signature)
.body(body.to_vec())
.send()
.await
}
}2. Provide it via Dioxus contextfn App() -> Element {
use_context_provider(|| SignedClient::new(b"your-secret-key"));
rsx! { DataLoader {} }
}
#[component]
fn DataLoader() -> Element {
let client = use_context::<SignedClient>();
let data = use_resource(move || {
let client = client.clone();
async move {
client.signed_request("https://api.example.com/data", b"{}").await
}
});
// render based on data...
}3. For encryptionWrap the request body with use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
use aes_gcm::aead::OsRng;
use aes_gcm::aead::rand_core::RngCore;
fn encrypt_body(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
let cipher = Aes256Gcm::new(key.into());
let mut nonce_bytes = [0u8; 12];
OsRng.fill_bytes(&mut nonce_bytes);
let nonce = aes_gcm::Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher.encrypt(nonce, plaintext).expect("encryption failed");
[nonce_bytes.to_vec(), ciphertext].concat()
}Cargo dependencies: [dependencies]
hmac = "0.12"
sha2 = "0.10"
hex = "0.4"
aes-gcm = "0.10"
reqwest = { version = "0.12", features = ["json"] } |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Typically, when sending API requests, there are some security measures in place, such as request signing and request encryption.
How to implement these functionalities by dioxus?
Beta Was this translation helpful? Give feedback.
All reactions