checkSameOrigin

Signature

def checkSameOrigin(allowed: HttpOriginRange.Default): Directive0

Description

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

Example

Checking the OriginOrigin header:

Scala
sourceval 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
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.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);
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.