CORS

Http4s provides Middleware, named CORS, for adding the appropriate headers to responses to allow Cross Origin Resource Sharing.

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: org.http4s.HttpRoutes[cats.effect.IO] = Kleisli(org.http4s.HttpRoutes$$$Lambda$29555/579117250@7c73e47e)

val request = Request[IO](Method.GET, Uri.uri("/"))
// request: org.http4s.Request[cats.effect.IO] = Request(method=GET, uri=/, headers=Headers())

service.orNotFound(request).unsafeRunSync
// res0: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0))

Now we can wrap the service in the CORS middleware.

import org.http4s.server.middleware._
val corsService = CORS(service)
// corsService: org.http4s.Http[[A]cats.data.OptionT[cats.effect.IO,A],cats.effect.IO] = Kleisli(org.http4s.server.middleware.CORS$$$Lambda$29726/597987132@760caf04)

corsService.orNotFound(request).unsafeRunSync
// res1: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0))

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 originHeader = Header("Origin", "https://somewhere.com")
// originHeader: org.http4s.Header.Raw = Origin: https://somewhere.com

val corsRequest = request.putHeaders(originHeader)
// corsRequest: request.Self = Request(method=GET, uri=/, headers=Headers(Origin: https://somewhere.com))

corsService.orNotFound(corsRequest).unsafeRunSync
// res2: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0, Access-Control-Expose-Headers: *, Vary: Origin,Access-Control-Request-Method, Access-Control-Allow-Credentials: true, Access-Control-Allow-Methods: GET, Access-Control-Allow-Origin: https://somewhere.com, Access-Control-Max-Age: 86400))

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 the default 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.uri("/"), headers = Headers.of(Header("Origin", "https://google.com")))
// googleGet: org.http4s.Request[cats.effect.IO] = Request(method=GET, uri=/, headers=Headers(Origin: https://google.com))

val yahooPut = Request[IO](Method.PUT, Uri.uri("/"), headers = Headers.of(Header("Origin", "https://yahoo.com")))
// yahooPut: org.http4s.Request[cats.effect.IO] = Request(method=PUT, uri=/, headers=Headers(Origin: https://yahoo.com))

val duckPost = Request[IO](Method.POST, Uri.uri("/"), headers = Headers.of(Header("Origin", "https://duckduckgo.com")))
// duckPost: org.http4s.Request[cats.effect.IO] = Request(method=POST, uri=/, headers=Headers(Origin: https://duckduckgo.com))

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 methodConfig = CORSConfig(
  anyOrigin = true,
  anyMethod = false,
  allowedMethods = Some(Set("GET", "POST")),
  allowCredentials = true,
  maxAge = 1.day.toSeconds)
// methodConfig: org.http4s.server.middleware.CORSConfig = CORSConfig(true,true,86400,false,org.http4s.server.middleware.CORSConfig$$$Lambda$29725/1494161900@1a61d28d,Some(Set(GET, POST)),Some(Set(Content-Type, Authorization, *)),Some(Set(*)))

val corsMethodSvc = CORS(service, methodConfig)
// corsMethodSvc: org.http4s.Http[[A]cats.data.OptionT[cats.effect.IO,A],cats.effect.IO] = Kleisli(org.http4s.server.middleware.CORS$$$Lambda$29726/597987132@16c59570)

corsMethodSvc.orNotFound(googleGet).unsafeRunSync
// res3: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0, Access-Control-Expose-Headers: *, Vary: Origin,Access-Control-Request-Method, Access-Control-Allow-Credentials: true, Access-Control-Allow-Methods: GET, POST, Access-Control-Allow-Origin: https://google.com, Access-Control-Max-Age: 86400))

corsMethodSvc.orNotFound(yahooPut).unsafeRunSync
// res4: org.http4s.Response[cats.effect.IO] = Response(status=403, headers=Headers())

corsMethodSvc.orNotFound(duckPost).unsafeRunSync
// res5: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0, Access-Control-Expose-Headers: *, Vary: Origin,Access-Control-Request-Method, Access-Control-Allow-Credentials: true, Access-Control-Allow-Methods: GET, POST, Access-Control-Allow-Origin: https://duckduckgo.com, Access-Control-Max-Age: 86400))

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”. allowedOrigins can use any expression that resolves into a boolean.

val originConfig = CORSConfig(
  anyOrigin = false,
  allowedOrigins = Set("https://yahoo.com", "https://duckduckgo.com"),
  allowCredentials = false,
  maxAge = 1.day.toSeconds)
// originConfig: org.http4s.server.middleware.CORSConfig = CORSConfig(false,false,86400,true,Set(https://yahoo.com, https://duckduckgo.com),None,Some(Set(Content-Type, Authorization, *)),Some(Set(*)))

val corsOriginSvc = CORS(service, originConfig)
// corsOriginSvc: org.http4s.Http[[A]cats.data.OptionT[cats.effect.IO,A],cats.effect.IO] = Kleisli(org.http4s.server.middleware.CORS$$$Lambda$29726/597987132@223ae418)

corsOriginSvc.orNotFound(googleGet).unsafeRunSync
// res6: org.http4s.Response[cats.effect.IO] = Response(status=403, headers=Headers())

corsOriginSvc.orNotFound(yahooPut).unsafeRunSync
// res7: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0, Access-Control-Expose-Headers: *, Vary: Origin,Access-Control-Request-Method, Access-Control-Allow-Credentials: false, Access-Control-Allow-Methods: PUT, Access-Control-Allow-Origin: https://yahoo.com, Access-Control-Max-Age: 86400))

corsOriginSvc.orNotFound(duckPost).unsafeRunSync
// res8: org.http4s.Response[cats.effect.IO] = Response(status=200, headers=Headers(Content-Length: 0, Access-Control-Expose-Headers: *, Vary: Origin,Access-Control-Request-Method, Access-Control-Allow-Credentials: false, Access-Control-Allow-Methods: POST, Access-Control-Allow-Origin: https://duckduckgo.com, Access-Control-Max-Age: 86400))

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

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