CORS

For security reasons, modern web browsers enforce a same origin policy, restricting the ability of sites from a given origin to access resources at a different origin. Http4s provides Middleware, named CORS, for adding the appropriate headers to responses to allow limited exceptions to this via cross origin resource sharing.

⚠️ Warning ⚠️

This guide assumes you are already familiar with CORS and its attendant security risks. By enabling CORS you are bypassing an important protection against malicious third-party websites - before doing so for any potentially sensitive resource, make sure you understand what you are doing and why.

Usage

Examples in this document have the following dependencies.

libraryDependencies ++= Seq(
  "org.http4s" %% "http4s-dsl" % http4sVersion,
  "org.http4s" %% "http4s-server" % http4sVersion
)

And we need some imports.

import cats.effect._
import org.http4s._
import org.http4s.dsl.io._
import org.http4s.implicits._

Let’s start by making a simple service.

val service = HttpRoutes.of[IO] {
  case _ =>
    Ok()
}
// service: HttpRoutes[IO] = Kleisli(
//   org.http4s.HttpRoutes$$$Lambda$8304/118025671@fc1f7a7
// )

val request = Request[IO](Method.GET, uri"/")
// request: Request[IO] = (
//   GET,
//   Uri(None, None, /, , None),
//   HttpVersion(1, 1),
//   Headers(),
//   Stream(..),
//   org.typelevel.vault.Vault@414544e8
// )

service.orNotFound(request).unsafeRunSync()
// res0: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0),
//   Stream(..),
//   org.typelevel.vault.Vault@3c6a1ad
// )

Now we can wrap the service in the CORS middleware.

import org.http4s.server.middleware._
val corsService = CORS.policy.withAllowOriginAll(service)
// corsService: Http[cats.data.OptionT[IO, A], IO] = Kleisli(
//   org.http4s.server.middleware.CORSPolicy$$Lambda$9235/1460667741@2987082d
// )

corsService.orNotFound(request).unsafeRunSync()
// res1: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0),
//   Stream(..),
//   org.typelevel.vault.Vault@297bae75
// )

So far, there was no change. That’s because an Origin header is required in the requests and it must include a scheme. This, of course, is the responsibility of the caller.

val corsRequest = request.putHeaders("Origin" -> "https://somewhere.com")
// corsRequest: request.Self = (
//   GET,
//   Uri(None, None, /, , None),
//   HttpVersion(1, 1),
//   Headers(Origin: https://somewhere.com),
//   Stream(..),
//   org.typelevel.vault.Vault@414544e8
// )

corsService.orNotFound(corsRequest).unsafeRunSync()
// res2: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
//   Stream(..),
//   org.typelevel.vault.Vault@42f2cdb6
// )

Notice how the response has the CORS headers added. How easy was that? And, as described in Middleware, services and middleware can be composed such that only some of your endpoints are CORS enabled.

Configuration

The example above showed one basic configuration for CORS, which adds the headers to any successful response, regardless of origin or HTTP method. There are configuration options to modify that.

First, we’ll create some requests to use in our example. We want these requests have a variety of origins and methods.

val googleGet = Request[IO](Method.GET, uri"/", headers = Headers("Origin" -> "https://google.com"))
// googleGet: Request[IO] = (
//   GET,
//   Uri(None, None, /, , None),
//   HttpVersion(1, 1),
//   Headers(Origin: https://google.com),
//   Stream(..),
//   org.typelevel.vault.Vault@748fd78c
// )
val yahooPut = Request[IO](Method.PUT, uri"/", headers = Headers("Origin" -> "https://yahoo.com"))
// yahooPut: Request[IO] = (
//   PUT,
//   Uri(None, None, /, , None),
//   HttpVersion(1, 1),
//   Headers(Origin: https://yahoo.com),
//   Stream(..),
//   org.typelevel.vault.Vault@65d87f50
// )
val duckPost = Request[IO](Method.POST, uri"/", headers = Headers("Origin" -> "https://duckduckgo.com"))
// duckPost: Request[IO] = (
//   POST,
//   Uri(None, None, /, , None),
//   HttpVersion(1, 1),
//   Headers(Origin: https://duckduckgo.com),
//   Stream(..),
//   org.typelevel.vault.Vault@11246d98
// )

Now, we’ll create a configuration that limits the allowed methods to GET and POST, pass that to the CORS middleware, and try it out on our requests.

import scala.concurrent.duration._
val corsMethodSvc = CORS.policy
  .withAllowOriginAll
  .withAllowMethodsIn(Set(Method.GET, Method.POST))
  .withAllowCredentials(false)
  .withMaxAge(1.day)
  .apply(service)
// corsMethodSvc: Http[cats.data.OptionT[IO, A], IO] = Kleisli(
//   org.http4s.server.middleware.CORSPolicy$$Lambda$9235/1460667741@45ef8d77
// )

corsMethodSvc.orNotFound(googleGet).unsafeRunSync()
// res3: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
//   Stream(..),
//   org.typelevel.vault.Vault@4fd601f1
// )
corsMethodSvc.orNotFound(yahooPut).unsafeRunSync()
// res4: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
//   Stream(..),
//   org.typelevel.vault.Vault@69d2d5a4
// )
corsMethodSvc.orNotFound(duckPost).unsafeRunSync()
// res5: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
//   Stream(..),
//   org.typelevel.vault.Vault@5ba83dab
// )

As you can see, the CORS headers were only added to the GET and POST requests. Next, we’ll create a configuration that limits the origins to “yahoo.com” and “duckduckgo.com”. withAllowOriginHost accepts an Origin.Host => Boolean. If you’re simply enumerating allowed hosts, a Set is convenient:

import org.http4s.headers.Origin

val corsOriginSvc = CORS.policy
  .withAllowOriginHost(Set(
    Origin.Host(Uri.Scheme.https, Uri.RegName("yahoo.com"), None),
    Origin.Host(Uri.Scheme.https, Uri.RegName("duckduckgo.com"), None)
  ))
  .withAllowCredentials(false)
  .withMaxAge(1.day)
  .apply(service)
// corsOriginSvc: Http[cats.data.OptionT[IO, A], IO] = Kleisli(
//   org.http4s.server.middleware.CORSPolicy$$Lambda$9235/1460667741@6215879c
// )

corsOriginSvc.orNotFound(googleGet).unsafeRunSync()
// res6: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Vary: Origin),
//   Stream(..),
//   org.typelevel.vault.Vault@1d33dba6
// )
corsOriginSvc.orNotFound(yahooPut).unsafeRunSync()
// res7: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: https://yahoo.com, Vary: Origin),
//   Stream(..),
//   org.typelevel.vault.Vault@62b34251
// )
corsOriginSvc.orNotFound(duckPost).unsafeRunSync()
// res8: Response[IO] = (
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Access-Control-Allow-Origin: https://duckduckgo.com, Vary: Origin),
//   Stream(..),
//   org.typelevel.vault.Vault@78ec6ec9
// )

Again, the results are as expected. You can, of course, create a configuration that combines limits on HTTP method, origin, and headers.

As described in Middleware, services and middleware can be composed such that only some of your endpoints are CORS enabled.