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 cats.implicits._
import org.http4s._
import org.http4s.dsl.io._
Let’s start by making a simple service.
val service = HttpService[IO] {
case _ =>
Ok()
}
// service: HttpService[IO] = Kleisli(
// org.http4s.HttpService$$$Lambda$12903/708292025@7a7fad56
// )
val request = Request[IO](Method.GET, uri("/"))
// request: Request[IO] = Request(
// Method("GET"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
service.orNotFound(request).unsafeRunSync
// res0: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
Now we can wrap the service in the CORS
middleware.
import org.http4s.server.middleware._
val corsService = CORS(service)
// corsService: HttpService[IO] = Kleisli(
// org.http4s.server.middleware.CORS$$$Lambda$13542/1582493812@5bd9f5db
// )
corsService.orNotFound(request).unsafeRunSync
// res1: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(Content-Length(0L)),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
So far, there was no change. That’s because an Origin
header is required
in the requests. This, of course, is the responsibility of the caller.
val originHeader = Header("Origin", "somewhere.com")
// originHeader: Header.Raw = Raw(Origin, "somewhere.com")
val corsRequest = request.putHeaders(originHeader)
// corsRequest: request.Self = Request(
// Method("GET"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(Raw(Origin, "somewhere.com")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
corsService.orNotFound(corsRequest).unsafeRunSync
// res2: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(
// Content-Length(0L),
// Raw(Access-Control-Expose-Headers, "*"),
// Raw(Vary, "Origin,Access-Control-Request-Methods"),
// Raw(Access-Control-Allow-Credentials, "true"),
// Raw(Access-Control-Allow-Methods, "GET"),
// Raw(Access-Control-Allow-Origin, "somewhere.com"),
// Raw(Access-Control-Max-Age, "86400")
// ),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
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 successul 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(Header("Origin", "google.com")))
// googleGet: Request[IO] = Request(
// Method("GET"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(Raw(Origin, "google.com")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
val yahooPut = Request[IO](Method.PUT, uri("/"), headers = Headers(Header("Origin", "yahoo.com")))
// yahooPut: Request[IO] = Request(
// Method("PUT"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(Raw(Origin, "yahoo.com")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
val duckPost = Request[IO](Method.POST, uri("/"), headers = Headers(Header("Origin", "duckduckgo.com")))
// duckPost: Request[IO] = Request(
// Method("POST"),
// Uri(None, None, "/", Query(), None),
// HttpVersion(1, 1),
// Headers(Raw(Origin, "duckduckgo.com")),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
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: CORSConfig = CORSConfig(
// true,
// true,
// 86400L,
// false,
// org.http4s.server.middleware.CORSConfig$$$Lambda$13541/470347447@29159d22,
// Some(Set("GET", "POST")),
// Some(Set("Content-Type", "*")),
// Some(Set("*"))
// )
val corsMethodSvc = CORS(service, methodConfig)
// corsMethodSvc: HttpService[IO] = Kleisli(
// org.http4s.server.middleware.CORS$$$Lambda$13542/1582493812@678352a9
// )
corsMethodSvc.orNotFound(googleGet).unsafeRunSync
// res3: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(
// Content-Length(0L),
// Raw(Access-Control-Expose-Headers, "*"),
// Raw(Vary, "Origin,Access-Control-Request-Methods"),
// Raw(Access-Control-Allow-Credentials, "true"),
// Raw(Access-Control-Allow-Methods, "GET, POST"),
// Raw(Access-Control-Allow-Origin, "google.com"),
// Raw(Access-Control-Max-Age, "86400")
// ),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
corsMethodSvc.orNotFound(yahooPut).unsafeRunSync
// res4: Response[IO] = Response(
// Status(403),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
corsMethodSvc.orNotFound(duckPost).unsafeRunSync
// res5: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(
// Content-Length(0L),
// Raw(Access-Control-Expose-Headers, "*"),
// Raw(Vary, "Origin,Access-Control-Request-Methods"),
// Raw(Access-Control-Allow-Credentials, "true"),
// Raw(Access-Control-Allow-Methods, "GET, POST"),
// Raw(Access-Control-Allow-Origin, "duckduckgo.com"),
// Raw(Access-Control-Max-Age, "86400")
// ),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
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("yahoo.com", "duckduckgo.com"),
allowCredentials = false,
maxAge = 1.day.toSeconds)
// originConfig: CORSConfig = CORSConfig(
// false,
// false,
// 86400L,
// true,
// Set("yahoo.com", "duckduckgo.com"),
// None,
// Some(Set("Content-Type", "*")),
// Some(Set("*"))
// )
val corsOriginSvc = CORS(service, originConfig)
// corsOriginSvc: HttpService[IO] = Kleisli(
// org.http4s.server.middleware.CORS$$$Lambda$13542/1582493812@60115612
// )
corsOriginSvc.orNotFound(googleGet).unsafeRunSync
// res6: Response[IO] = Response(
// Status(403),
// HttpVersion(1, 1),
// Headers(),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
corsOriginSvc.orNotFound(yahooPut).unsafeRunSync
// res7: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(
// Content-Length(0L),
// Raw(Access-Control-Expose-Headers, "*"),
// Raw(Vary, "Origin,Access-Control-Request-Methods"),
// Raw(Access-Control-Allow-Credentials, "false"),
// Raw(Access-Control-Allow-Methods, "PUT"),
// Raw(Access-Control-Allow-Origin, "yahoo.com"),
// Raw(Access-Control-Max-Age, "86400")
// ),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
corsOriginSvc.orNotFound(duckPost).unsafeRunSync
// res8: Response[IO] = Response(
// Status(200),
// HttpVersion(1, 1),
// Headers(
// Content-Length(0L),
// Raw(Access-Control-Expose-Headers, "*"),
// Raw(Vary, "Origin,Access-Control-Request-Methods"),
// Raw(Access-Control-Allow-Credentials, "false"),
// Raw(Access-Control-Allow-Methods, "POST"),
// Raw(Access-Control-Allow-Origin, "duckduckgo.com"),
// Raw(Access-Control-Max-Age, "86400")
// ),
// Stream(..),
// org.http4s.AttributeMap@8cf85da
// )
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.