0

I have a RESTFul service written in Finch framework with multiple endpoints. Some of the endpoints needs to support JSONP for cross domain requests. By checking the source code of Finch it looks like there is not an easy way of doing so. I've found this page kind of related but not quite knowing the details.

https://groups.google.com/forum/#!topic/finaglers/nAaCfOiLp1w

Can someone give me some guideline/example ? My return value want to be look like:

{
    ids:[id1,id2,id3...idn]
}
Shi Chen
  • 21
  • 2

1 Answers1

1

Not going into the details on why JSONP considered insecure (I assume you know that already), the Finaglers thread you're referencing mentions JsonpFilter that can be applied to an HTTP service returning JSON to "upgrade" it to JSONP.

Here is a small example on how to wire this filter with Finch's endpoint.

import com.twitter.finagle.Http
import com.twitter.finagle.http.filter.JsonpFilter
import io.finch._
import io.finch.circe._

val endpoint: Endpoint[Map[String, String]] = get("jsonp") {
  Ok(Map("foo" -> "bar"))
}

val service = endpoint.toServiceAs[Application.Json]

Http.server.serve(":8080", JsonpFilter.andThen(service))

JsonpFilter is dead simple. It checks the returned HTTP payload and it's a JSON string, it wraps it with a call to a function whose name is passed in the callback query-string param (and changes the content-type to application/javascript correspondingly). Using httpie, this would look as:

$ http :8081/jsonp
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Length: 39
Content-Type: application/json

{
    "foo": "bar"
}

$ http :8080/jsonp?callback=myfunction 
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Length: 56
Content-Type: application/javascript

/**/myfunction({"foo":"bar"});
Vladimir Kostyukov
  • 2,492
  • 3
  • 21
  • 30
  • Thanks a lot Vlad. This is exactly what I wanted. I was looking for where to define the callback but until reading your answer, did not realize JsonpFilter automatically adds it. It is a stupid idea to put every web service call in the browser. Any suggestions whether or not I should push back really hard to ask the clients to call our API in there backend for X-domain calls? We cannot afford the backward compatibility problem by using CORS. – Shi Chen Nov 09 '16 at 18:06
  • Hmm, wait, still have some problem: – Shi Chen Nov 09 '16 at 18:54