expression
WebSocket: check an allowed browser origin
For browser-facing endpoints, compare Origin with an explicit allowlist before upgrading. This policy denies absent or mismatched origins; other client types may need a separate policy. Origin does not authenticate a user and non-browser clients may forge it. Standalone synthetic example. Expected stdout (not executed): false true false Common mistake: Accepting origins with a loose prefix match or using Origin as proof of identity.
Formal Syntax & Structure
rust syntaxrust
headers.get(ORIGIN).and_then(|v| v.to_str().ok())Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::http::{HeaderMap, HeaderValue, header::ORIGIN}; fn allowed(h: &HeaderMap) -> bool { h.get(ORIGIN).and_then(|v| v.to_str().ok()) == Some("https://app.example.test") } let mut h = HeaderMap::new(); println!("{}", allowed(&h)); h.insert(ORIGIN, HeaderValue::from_static("https://app.example.test")); println!("{}", allowed(&h)); h.insert(ORIGIN, HeaderValue::from_static("https://app.example.test.invalid")); println!("{}", allowed(&h));}