Reputation: 51
How to add origin to websocket client "connect_async" in backend Tauri?
Just like in JavaScript, it is easy to set the origin in the websocket backend:
const ws = new WebSocket(
"wss://server.example.com",
{ origin: "https://example.com" }
);
And how do you add an Origin header to the client in Rust in the Tauri backend?
I'm using the library tokio-tungstenite.
let (mut ws_remote, _) = connect_async(
Url::parse("wss://server.example.com").expect("Can't connect to URL"),
).await?;
Upvotes: 1
Views: 2289
Reputation: 153
You can let tungstenite build the request for you via into_client_request()
:
use anyhow::Result;
use tokio_tungstenite::{connect_async, tungstenite::client::IntoClientRequest};
#[tokio::main]
async fn main() -> Result<()> {
let mut request = "wss://server.example.com".into_client_request()?;
let headers = request.headers_mut();
headers.insert("Origin", "https://example.com".parse().unwrap());
let (socket_stream) = connect_async(request).await?;
Ok(())
}
So there is no need to manually generate a key or specify the websocket version.
Upvotes: 4
Reputation: 51
@isaactfa Thank you for answer, I corrected a little and it works now.
let request = Request::builder()
.method("GET")
.header("Host", "wss://example.com")
.header("Origin", "https://example.com/")
.header("Connection", "Upgrade")
.header("Upgrade", "websocket")
.header("Sec-WebSocket-Version", "13")
.header("Sec-WebSocket-Key", tungstenite::handshake::client::generate_key())
.uri("wss://example.com")
.body(())?;
let (mut ws_remote, _) = connect_async(request).await?;
Upvotes: 1
Reputation: 6657
You can use a http::Request
instead of just a Url
:
use http::Request;
use tokio_tungstenite;
let request = Request::builder()
.uri("wss://server.example.com")
.header("Origin", "https://example.com")
.body(())?;
let (mut ws_remote, _) = tokio_tungstenite::connect_async(request).await?;
Upvotes: 0