checkSameOrigin

Signature

def checkSameOrigin(allowed: HttpOriginRange.Default): Directive0

Description

Checks that request comes from the same origin. Extracts the Origin header value and verifies that allowed range contains the obtained value. In the case of absent of the Origin header rejects with a MissingHeaderRejection. If the origin value is not in the allowed range rejects with an InvalidOriginHeaderRejection and StatusCodes.Forbidden status.

Example

val correctOrigin = HttpOrigin("http://localhost:8080")
val route = checkSameOrigin(HttpOriginRange(correctOrigin)) {
  complete("Result")
}

// tests:
// handle request with correct origin headers
Get("abc") ~> Origin(correctOrigin) ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "Result"
}

// reject request with missed origin header
Get("abc") ~> route ~> check {
  inside(rejection) {
    case MissingHeaderRejection(headerName) ⇒ headerName shouldEqual Origin.name
  }
}

// rejects request with invalid origin headers
val invalidHttpOrigin = HttpOrigin("http://invalid.com")
val invalidOriginHeader = Origin(invalidHttpOrigin)
Get("abc") ~> invalidOriginHeader ~> route ~> check {
  inside(rejection) {
    case InvalidOriginRejection(allowedOrigins) ⇒
      allowedOrigins shouldEqual Seq(correctOrigin)
  }
}
Get("abc") ~> invalidOriginHeader ~> Route.seal(route) ~> check {
  status shouldEqual StatusCodes.Forbidden
  responseAs[String] should include(s"${correctOrigin.value}")
}
The source code for this page can be found here.