If I have a web application connecting to a remove Active MQ server, how can I enable CORS to permit cross-domain communication?
2 Answers
This took me quite a while to work out, and is not obvious, so I'll document the changes here. This has been done with ActiveMQ 5.10.
First, you'll need a CORS filter to add the appropriate headers to the responses. I tried using the built in Jetty cors filter (http://wiki.eclipse.org/Jetty/Feature/Cross_Origin_Filter), but I have a feeling that it wasn't responding to the POST preflight OPTION requests properly. However, there was a second issue that was preventing my CORS connections, so don't take my word for it that the Jetty CORS filter doesn't work (I abandoned it and didn't try it again).
Instead I used the filter at http://software.dzhuvinov.com/cors-filter.html. Note that version 2.2.1 of this library does not work (it duplicates headers like Access-Control-Allow-Origin, which is not permitted), however a small fix (replacing addHeader with setHeader) was all that it took to make it work. See https://github.com/AutoGeneral/cors-filter for the fixed code.
Now you need to update the amq_jquery_adapter.js file to include the xhrFields withCredentials field (see CORS request - why are the cookies not sent?). So the code looks like this:
ajax: function(uri, options) {
request = {
url: uri,
data: options.data,
success: options.success || function(){},
error: options.error || function(){},
xhrFields: {
withCredentials: true
}
}
So, with your CORS filter and the updated jQuery ajax request settings, you'll be able to make CORS requests to the AJAX servlet.
It seems this way of setting withCredentals did not work for me. I used the jetty CORS servlets, and set the withCredentials this way, only then it started workng: xhr.withCredentials = true;
And on the server side in the web.xml:
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter- class>
<init-param>
<param-name>allowedOrigins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>allowedMethods</param-name>
<param-value>GET,POST,HEAD,OPTIONS</param-value>
</init-param>
<init-param>
<param-name>allowedHeaders</param-name>
<param-value>X-Requested-With,Content-Type,Accept,Origin</param-value>
</init-param>
<init-param>
<param-name>allowedCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

- 21
- 1
- 3