How do I implement akka-http-cors correctly to be able to allow access from any origin (domain, in my case localhost:3000) to a Https Server (Scala/Akka)?
Based on the akka-http-cors documentation should defaultSettings do the job, but I am still doing something wrong:
...
import ch.megard.akka.http.cors.scaladsl.CorsDirectives._
var settings = CorsSettings.defaultSettings
lazy val theRequestRoutes: Route =
cors(settings) {
pathPrefix("getsearchresult") {
post {
entity(as[Server.ReqGetSearchResult]) { request: ReqGetSearchResult =>
val operationPerformed: Future[Server.ServerResponse] = controller.ask(ControllerActor.Request_GetSearchResult(_, request))
onSuccess(operationPerformed) {
case Server.Send_Response_Success(jsonResponse) => complete(jsonResponse)
case Server.Send_Response_Failure(status) => complete("""{"status":"server_error"}""")
}
}
}
}
}
...
val https: HttpsConnectionContext = getHttpsConnectionContext()
val serverBinding: Future[Http.ServerBinding] = Http().newServerAt(host, port).enableHttps(https).bind(theRequestRoutes)
libraryDependencies = "ch.megard" %% "akka-http-cors" % "1.1.2"
Google Chrome Error:
Access to XMLHttpRequest at 'https://api.domain.com:8080/getsearchresult' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Firefox Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.domain.com:8080/getsearchresult. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
akka-http-core: https://github.com/lomigmegard/akka-http-cors#configuration
Any help is highly appreciated!
CodePudding user response:
The problem in my case was that I haven't done Marshalling in the right way, thereby it crashed in following line:
entity(as[Server.ReqGetSearchResult]) { request: ReqGetSearchResult =>
Surprisingly to me, that the error is than labeled as CORS error.
I solved it by checking the Akka HTTP JSON Support manual: https://doc.akka.io/docs/akka-http/current/common/json-support.html
It now works for me in my case by having this upfront:
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val clientRequestFormat = jsonFormat5(Server.ReqGetSearchResult)
}
class RequestRoutes(controller: ActorRef[Controller.Command])(implicit system: ActorSystem[_]) extends Directives with JsonSupport {
import akka.actor.typed.scaladsl.AskPattern.schedulerFromActorSystem
import akka.actor.typed.scaladsl.AskPattern.Askable
implicit val timeout: Timeout = 60.seconds
... (code from above)
}
CodePudding user response:
Check this gist URL ~ https://gist.github.com/hakimkal/bd5ca349ef10e8981e121eb865023067
This is my Main.scala file use of the above trait
val cors = new CORSHandler {}
val route = new MerchantRoutes(merchantService, authService)
val serverBinding = Http()
.newServerAt(host, port)
.bind(
cors.corsHandler(route.merchantRoutes)
)