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.
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._
If you're in a REPL, we also need a runtime:
import cats.effect.unsafe.IORuntime
implicit val runtime: IORuntime = cats.effect.unsafe.IORuntime.global
Let's start by making a simple service.
val service = HttpRoutes.of[IO] {
case _ => Ok()
}
val request = Request[IO](Method.GET, uri"/")
service.orNotFound(request).unsafeRunSync()
// res0: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0),
// = Stream(..),
// = org.typelevel.vault.Vault@4f98f9ab
// )
Now we can wrap the service in the CORS
middleware.
import org.http4s.server.middleware._
val corsService = CORS.policy.withAllowOriginAll(service)
corsService.orNotFound(request).unsafeRunSync()
// res1: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0),
// = Stream(..),
// = org.typelevel.vault.Vault@1bb01312
// )
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(scheme = None, authority = None, path = /, query = , fragment = None),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Origin: https://somewhere.com),
// = Stream(..),
// = org.typelevel.vault.Vault@7eac4445
// )
corsService.orNotFound(corsRequest).unsafeRunSync()
// res2: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
// = Stream(..),
// = org.typelevel.vault.Vault@3b594576
// )
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(scheme = None, authority = None, path = /, query = , fragment = None),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Origin: https://google.com),
// = Stream(..),
// = org.typelevel.vault.Vault@66fe8772
// )
val yahooPut = Request[IO](Method.PUT, uri"/",
headers = Headers("Origin" -> "https://yahoo.com"))
// yahooPut: Request[IO] = (
// = PUT,
// = Uri(scheme = None, authority = None, path = /, query = , fragment = None),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Origin: https://yahoo.com),
// = Stream(..),
// = org.typelevel.vault.Vault@4bbd858e
// )
val duckPost = Request[IO](Method.POST, uri"/",
headers = Headers("Origin" -> "https://duckduckgo.com"))
// duckPost: Request[IO] = (
// = POST,
// = Uri(scheme = None, authority = None, path = /, query = , fragment = None),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Origin: https://duckduckgo.com),
// = Stream(..),
// = org.typelevel.vault.Vault@606f13e
// )
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.orNotFound(googleGet).unsafeRunSync()
// res3: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
// = Stream(..),
// = org.typelevel.vault.Vault@2394b5d7
// )
corsMethodSvc.orNotFound(yahooPut).unsafeRunSync()
// res4: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
// = Stream(..),
// = org.typelevel.vault.Vault@6624df5f
// )
corsMethodSvc.orNotFound(duckPost).unsafeRunSync()
// res5: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: *),
// = Stream(..),
// = org.typelevel.vault.Vault@1ecc0b85
// )
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.orNotFound(googleGet).unsafeRunSync()
// res6: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Vary: Origin),
// = Stream(..),
// = org.typelevel.vault.Vault@1b613553
// )
corsOriginSvc.orNotFound(yahooPut).unsafeRunSync()
// res7: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: https://yahoo.com, Vary: Origin),
// = Stream(..),
// = org.typelevel.vault.Vault@5f6540a0
// )
corsOriginSvc.orNotFound(duckPost).unsafeRunSync()
// res8: Response[[A]IO[A]] = (
// = Status(code = 200),
// = HttpVersion(major = 1, minor = 1),
// = Headers(Content-Length: 0, Access-Control-Allow-Origin: https://duckduckgo.com, Vary: Origin),
// = Stream(..),
// = org.typelevel.vault.Vault@5a333a69
// )
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.