Created
December 5, 2018 21:30
-
-
Save kmikulski/f2a294c9df3eb733f2b75bf83ec22d0d to your computer and use it in GitHub Desktop.
the description for this gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.http.scaladsl.model.HttpMethods._ | |
import akka.http.scaladsl.model.headers._ | |
import akka.http.scaladsl.model.{ HttpResponse, StatusCodes } | |
import akka.http.scaladsl.server.Directives.{ complete, 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")) | |
private def addAccessControlHeaders: Directive0 = { | |
respondWithHeaders(corsResponseHeaders) | |
} | |
private def preflightRequestHandler: Route = options { | |
complete(HttpResponse(StatusCodes.OK). | |
withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE))) | |
} | |
def corsHandler(r: Route): Route = addAccessControlHeaders { | |
preflightRequestHandler ~ r | |
} | |
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