Handling CORS in Akka HTTP
This tutorial shows a quick way for you to handle CORS requests in Akka HTTP-based microservices, with the added bonus of adding CORS headers to any HttpResponse.
Join the DZone community and get the full member experience.
Join For FreeHere’s a quick tip for handling CORS requests in your Akka HTTP based microservice:
Create the following trait – CORSHandler
Handler for your Akka Http RoutesScala
trait CORSHandler{
private val corsResponseHeaders = List(
`Access-Control-Allow-Origin`.*,
`Access-Control-Allow-Credentials`(true),
`Access-Control-Allow-Headers`("Authorization",
"Content-Type", "X-Requested-With")
)
//this directive adds access control headers to normal responses
private def addAccessControlHeaders: Directive0 = {
respondWithHeaders(corsResponseHeaders)
}
//this handles preflight OPTIONS requests.
private def preflightRequestHandler: Route = options {
complete(HttpResponse(StatusCodes.OK).
withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
}
// Wrap the Route with this method to enable adding of CORS headers
def corsHandler(r: Route): Route = addAccessControlHeaders {
preflightRequestHandler ~ r
}
// Helper method to add CORS headers to HttpResponse
// preventing duplication of CORS headers across code
def addCORSHeaders(response: HttpResponse):HttpResponse =
response.withHeaders(corsResponseHeaders)
}
To use this trait in an actual route, we take the example route given in the Akka documentation and wrap the route with our corsHandler
method defined in the above trait, as follows:
ng CORSHandler in RouteScala
get {
// Using the CORSHandler in our actual routes
corsHandler(
pathSingleSlash {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
"<html><body>Hello world!</body></html>"))
} ~
path("ping") {
complete("PONG!")
} ~
path("crash") {
sys.error("BOOM!")
}
)
}
Explanation
This trait gives us a simple way to add the CORS headers to every response that this route sends back. This CORSHandler
, apart from adding response headers is also responsible for handling OPTIONS HTTP request (the preflight request) for which it sends back a 200 OK
response with the header Access-Control-Allow-Methods
specifying which HTTP methods can be used in subsequent calls as per the CORS specification.
This trait has a bonus method for adding CORS Headers to any HttpResponse, which is created from somewhere else in your application, say from an Exception or Rejection Handler where the response is created and sent back from a different flow than the normal route flow.
That’s it for today. Happy hacking!
Published at DZone with permission of Agraj Mangal, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments