Skip to content

Commit ac22bb3

Browse files
authored
Merge pull request #439 from rkusa/cors-fix-origin-not-set
Fix CORS behaviour if there is no origin header
2 parents a31b69e + ce947f9 commit ac22bb3

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/middleware/cors.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,16 @@ impl Cors {
149149
impl<State: Send + Sync + 'static> Middleware<State> for Cors {
150150
fn handle<'a>(&'a self, req: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
151151
Box::pin(async move {
152-
let origins = req
153-
.header(&headers::ORIGIN)
154-
.cloned()
155-
.unwrap_or_else(|| vec!["".parse::<HeaderValue>().unwrap()]);
152+
let origins = req.header(&headers::ORIGIN).cloned().unwrap_or_default();
156153

157154
// TODO: how should multiple origin values be handled?
158-
let origin = &origins[0];
155+
let origin = match origins.first() {
156+
Some(origin) => origin,
157+
None => {
158+
// This is not a CORS request if there is no Origin header
159+
return next.run(req).await;
160+
}
161+
};
159162

160163
if !self.is_valid_origin(origin) {
161164
return http_types::Response::new(StatusCode::Unauthorized).into();
@@ -395,7 +398,7 @@ mod test {
395398
#[test]
396399
fn not_set_origin_header() {
397400
let mut app = app();
398-
app.middleware(Cors::new());
401+
app.middleware(Cors::new().allow_origin(ALLOW_ORIGIN));
399402

400403
let request = http_types::Request::new(http_types::Method::Get, endpoint_url());
401404

0 commit comments

Comments
 (0)