Created
November 10, 2014 02:08
-
-
Save sap1ens/390da29f60c5f0458369 to your computer and use it in GitHub Desktop.
CORS support for Spray-based APIs
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
package co.bench.api.spray | |
import spray.routing.{Directives, Route} | |
import spray.http.HttpHeaders.{`Access-Control-Allow-Credentials`, `Access-Control-Allow-Headers`, `Access-Control-Allow-Methods`, `Access-Control-Allow-Origin`} | |
import spray.http.{StatusCodes, HttpOrigin, SomeOrigins} | |
import spray.http.HttpMethods._ | |
trait CORSSupport extends Directives { | |
private val CORSHeaders = List( | |
`Access-Control-Allow-Methods`(GET, POST, PUT, DELETE, OPTIONS), | |
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"), | |
`Access-Control-Allow-Credentials`(true) | |
) | |
def respondWithCORS(origin: String)(routes: => Route) = { | |
val originHeader = `Access-Control-Allow-Origin`(SomeOrigins(Seq(HttpOrigin(origin)))) | |
respondWithHeaders(originHeader :: CORSHeaders) { | |
routes ~ options { complete(StatusCodes.OK) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment