checkSameOrigin

checkSameOrigin

§Signature

§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

  1. val correctOrigin = HttpOrigin("http://localhost:8080")
  2. val route = checkSameOrigin(HttpOriginRange(correctOrigin)) {
  3. complete("Result")
  4. }
  5.  
  6. // tests:
  7. // handle request with correct origin headers
  8. Get("abc") ~> Origin(correctOrigin) ~> route ~> check {
  9. status shouldEqual StatusCodes.OK
  10. responseAs[String] shouldEqual "Result"
  11. }
  12.  
  13. // reject request with missed origin header
  14. Get("abc") ~> route ~> check {
  15. inside(rejection) {
  16. case MissingHeaderRejection(headerName) headerName shouldEqual Origin.name
  17. }
  18. }
  19.  
  20. // rejects request with invalid origin headers
  21. val invalidHttpOrigin = HttpOrigin("http://invalid.com")
  22. val invalidOriginHeader = Origin(invalidHttpOrigin)
  23. Get("abc") ~> invalidOriginHeader ~> route ~> check {
  24. inside(rejection) {
  25. case InvalidOriginRejection(allowedOrigins)
  26. allowedOrigins shouldEqual Seq(correctOrigin)
  27. }
  28. }
  29. Get("abc") ~> invalidOriginHeader ~> Route.seal(route) ~> check {
  30. status shouldEqual StatusCodes.Forbidden
  31. responseAs[String] should include(s"${correctOrigin.value}")
  32. }