checkSameOrigin
Description
Checks that request comes from the same origin. Extracts the Origin
Origin
header value and verifies that allowed range contains the obtained value. In the case of absent of the Origin
Origin
header rejects with a MissingHeaderRejection
MissingHeaderRejection
. If the origin value is not in the allowed range rejects with an InvalidOriginHeaderRejection
and StatusCodes.Forbidden
StatusCodes.FORBIDDEN
status.
Example
Checking the Origin
Origin
header:
- Scala
-
source
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}") }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.complete; import static org.apache.pekko.http.javadsl.server.Directives.checkSameOrigin; final HttpOrigin validOriginHeader = HttpOrigin.create("http://localhost", Host.create("8080")); final HttpOriginRange validOriginRange = HttpOriginRange.create(validOriginHeader); final TestRoute route = testRoute(checkSameOrigin(validOriginRange, () -> complete("Result"))); route .run(HttpRequest.create().addHeader(Origin.create(validOriginHeader))) .assertStatusCode(StatusCodes.OK) .assertEntity("Result"); route.run(HttpRequest.create()).assertStatusCode(StatusCodes.BAD_REQUEST); final HttpOrigin invalidOriginHeader = HttpOrigin.create("http://invalid.com", Host.create("8080")); route .run(HttpRequest.create().addHeader(Origin.create(invalidOriginHeader))) .assertStatusCode(StatusCodes.FORBIDDEN);
1.1.0