Skip to content

Instantly share code, notes, and snippets.

@hakimkal
Last active November 30, 2021 08:50
Show Gist options
  • Select an option

  • Save hakimkal/bd5ca349ef10e8981e121eb865023067 to your computer and use it in GitHub Desktop.

Select an option

Save hakimkal/bd5ca349ef10e8981e121eb865023067 to your computer and use it in GitHub Desktop.
CORS Handler for Akka Web Module
package ng.lep.web.routes
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{
`Access-Control-Allow-Credentials`,
`Access-Control-Allow-Headers`,
`Access-Control-Allow-Methods`,
`Access-Control-Allow-Origin`
}
import akka.http.scaladsl.model.{ HttpResponse, StatusCodes }
import akka.http.scaladsl.server.Directives.{ complete, concat, options, respondWithHeaders }
import akka.http.scaladsl.server.{ Directive0, Route }
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 {
concat(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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment