Add CORS handling for running from a local dev server (#3612)

This commit is contained in:
user411 2021-08-27 06:57:36 -06:00 committed by GitHub
parent 0746b14331
commit 55c57c487e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 2 deletions

View file

@ -0,0 +1,45 @@
package org.bitcoins.server.routes
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
/** Add CORS handling for accessing backend over localhost from modern browsers
* @see dzone.com/articles/handling-cors-in-akka-http
*/
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)
}

View file

@ -18,7 +18,8 @@ case class Server(
handlers: Seq[ServerRoute],
rpcbindOpt: Option[String],
rpcport: Int)(implicit system: ActorSystem)
extends HttpLogger {
extends HttpLogger
with CORSHandler {
import system.dispatcher
@ -54,7 +55,7 @@ case class Server(
handleRejections(rejectionHandler) {
handleExceptions(exceptionHandler) {
route
corsHandler(route)
}
}
}