Tomcat CORS not working in FireFox - ajax

I have a REST API deployed on Tomcat 8.0.15, I added a CORS filter in order to activate cross domain requests.
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>DAV, content-length, Allow</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Client side :
function testF3(){
var user = { "login": "test", "password": "test*1" } ;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'https://xxxxxx/login',// Use xxxx to mask the URL
crossDomain: true,
data: JSON.stringify( user ),
dataType:'text',
success: function(data)
{
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('Fired');
console.log(errorThrown+" // "+textStatus);
}
});
}
Everything is working fine, I have tested this in Chrome 40.0.2214.115 ,Opera 28.0.1750.40 and Safari 5.1.7 and get the result as expected.
I did the same thing with FireFox 36.0.1 but I got errors in the console stating that OPTIONS request was aborted. Please check the image below for more details :
I tried in vain to change the CORS filter in my web.xml, add and remove supported Headers .. But no result...
Please any help will be very appreciated.
Many thanks guys.

Related

Servlet mapping issue with websphere

Following is my servlet mapping:
Path: EAR/WAR/WEB-INF/web.xml
<servlet>
<servlet-name>GetChartDetails</servlet-name>
<servlet-class>com.high.GetChartDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetChartDetails</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Following in the location of my JSP:
Path: war/Monitor/XYZ.jsp
Inside this jsp, I am trying to make ajax call by calling above servlet as follows:
$.ajax({
type: "GET",
url:"http://localhost:25014/Monitor/GetChartDetails? jsonp="+chartType,
dataType: 'jsonp',
jsonpCallback: chartType,
error: function () {
alert("Error is occured");
}
});
chartType is a string. I am getting the alert as "Error is occured" and servlet is not being called.
Can someone please help me with this. Thank you.

Ajax Response to preflight request doesn't pass access control

I have been looking for 5 hours or so but i give up.
my ajax get request just does't want to work.
var ApiResponce = $.ajax({
url: "http://localhost:18428/api/Reservation/" + userid + "?weekNumber=" + weeknr,
type: 'GET',
headers: {
'Authorization': "bearer " + token,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
dataType: 'json',
crossDomain: true,
contentType: "application/json",
success: function(responce) {
console.log("success");
console.log(responce);
},
error: function(err) {
console.log("error");
console.log(ApiResponce);
},
});
it connecting to a standard C# mvc api but all that i am getting is this error:
XMLHttpRequest cannot load http://localhost:18428/api/Reservation/1?weekNumber=1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.
If you're using Apache Tomcat in server side you need to edit your web.xml file on your servlet container and add the following lines:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials,X-Bonita-API-Token</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,X-Bonita-API-Token</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Note: Works in Apache Tomcat 7+, Don't forget restart tomcat.

jQuery Ajax POST call with JSON in Rest Web Service Issue

I want to post a JSON object from my page to a Rest WS. But when I am posting json through jQuery ajax call as output I am getting a HTML page with "HTTP Status 405 - Method Not Allowed" instate of JSON, which I am sending from Rest Web Service. Please refer the following code snippet.
I am using jquery 1.11.3 version.
http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
jQuery Ajax Call:
$.ajax({
url: "http://localhost:8080/MyWebService/api/myService/jsonpost",
method: "POST",
data: jsonObj,
dataType: 'application/json',
contentType: "application/json",
success: function(result){
alert(result);
},
error(){
console.log('Error');
}
});
Please note my rest web service is running in my local tomcat.
Please find my Rest Web Service POST code.
#POST
#Path("/jsonpost")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String crunchifyJsonPostREST(SampleVO input) throws JSONException{
SampleVO sampleVO = input;
return new Gson().toJson(sampleVO);
}
VO:
public class SampleVO {
private String name;
/**
* #return the name
*/
#XmlElement
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
My Maven Dependency is:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
Firebug Details:
Please find my ajax request Header.
Please find my ajax response and response HTML.
Need your help to resolve this issue.
Thanks is advance.
Solution:
After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet
After lot of googling I have found some solution. Now I am using HTTP-Proxy-Servlet.
I have crated a java web application with my html page which has the ajax call and from my ajax call I am calling a URL of same domain. Please refer my ajax call.
$.ajax({
url: "rest/api/crunchifyService/jsonpost",
method: "POST",
data: JSON.stringify(jsonObj),
dataType: 'json',
contentType: "application/json",
success: function(result,status,jqXHR ){
//Do something
},
error(jqXHR, textStatus, errorThrown){
//Do something
}
});
Now I have done this same domain call mapping with org.mitre.dsmiley.httpproxy.ProxyServlet. Please refer my web xml.
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
<init-param>
<param-name>targetUri</param-name>
<param-value><!-- Cross domain URL goes here --></param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Now my ajax is calling this Proxy Servlet and it is redirecting to the CROS destination Rest Web Service.
Please refer the following URL, you will get more details.
https://github.com/mitre/HTTP-Proxy-Servlet
datatype should be dataType: 'json'
If you are using contentType: "application/json", , then you should stringify your data.
data:JSON.stringify(jsonObj),
Try using type & contentType settings of ajax:
type:'POST',
contentType: 'application/json',
Example:
function loadDoc(){
var num = '{"empid": 45,"name": "gaurav","salary":566.55}';
$.ajax({
url: 'http://localhost:9029/addS',
method: 'POST',
type:'POST',
contentType: 'application/json',
success: function(response){
console.log("response::::"+response);
$("#output").text(response);
},
error: function( jqXHR,textStatus, errorThrown){
console.log("Error askdjk");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}

No Access-Control-Allow-Origin - Cross Domain

I am wanting to access a service which is queried from AJAX, but when I call this service indicates me the following in the console browser:
XMLHttpRequest cannot load http://192.168.108.166:8080/LdapRESTEasy/rest/RESTEasyLdap/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
I'm working with Apache Tomcat 6 and create a service which I RESTeasy returns a JSON with user data when login.
My javascript code which contains the AJAX is as follows:
function login(){
var hashNoEnconding = document.getElementById("user").value +'|'+ document.getElementById("pass").value;
var hashEnconding = base64Encode(hashNoEnconding);
var url = "http://192.168.108.166:8080/LdapRESTEasy/rest/RESTEasyLdap/login";
$.ajax({
url:url,
type:'POST',
encoding:"UTF-8",
headers: {
"Content-Type":"application/json; charset=UTF-8"
},
contentType: "application/json; charset=UTF-8",
accept: "application/json; charset=UTF-8",
cacheControl: "no-cache",
beforeSend: function (request){
request.setRequestHeader("authorization", hashEnconding);
},
success:function (data, status, xhr) {
},
error: function (data) {
}
});
}
From the apache tomcat server configure the web.xml which recommend adding the CORS filters
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Content-Type, X-Requested-With, Accept, Authentication, Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I also added the apache libraries in / lib:
cors-filter-1.9.2.jar
java-property-utils-1.9.jar
I have read in the internet about this problem, but still fails to solve
Please, Can I help me?
Thanks!!
Yah I found the solution. The problem is in error 500 Internal Server which indicated to me that the parameter sent by request did not reach the service. The same appeared as NULL.
I modify the service to receive a GET and it worked!

Authentication headers are not sending JQuery Ajax

I have web server hosted in Apache Tomcat 7 with Basic authentication. I have Tomcat user 'tomcat' with role 'tomcat' and password 'tomcat'. Following are my web.xml file and script snippet in client side respectively.
Web.xml
<?xml version="1.0" encoding="ASCII"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>testservice</display-name>
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>testservice</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testservice</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>testservice</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>tomcat</role-name>
</auth-constraint>
<user-data-constraint>
<!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
Client script:
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
</script>
I'm pretty sure about that there's no problem with Web Service and Basic authentication. But from client script, no authentication headers are sending. I tried header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==") too. But request is sending without authentication headers. Any help will be appreciated.
Two things to try:
1) Add the CORS Filter to your Tomcat configuration
add the CORS Filter to your Tomcat configuration. Note Access-Control-Allow-Origins has been purposely left blank below, so no site has access via CORS. But the important parameter that is configured is Access-Control-Allow-Credentials.
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2) Modify Your Ajax Call
Modify your beforeSend in your ajax call like so:
$.ajax({
type: "GET",
beforeSend: function (request)
{
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
Only other thing I noticed is that your web.xml might also need the following:
<security-role>
<role-name>tomcat</role-name>
</security-role>
Hope this helps.
Found that passing authentication via headers is not working with jQuery ajax with jsonp data type. So tried following and works fine.
$.ajax({
type: "GET",
url: "http://tomcat:tomcat#localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
success: function(res) {
alert(res);
},
error: function(err) {
alert(err);
}
});
function callbackMethod(data) {
alert(data);
}
mccannf got us 99% of the way there with a similar issue hover we switched up how we set the withCredentials property and this worked for us. notice we set the xhrFields property. This can been seen within the jQuery documentation for the ajax method here; http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
xhrFields: { withCredentials: true },
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
url: "http://localhost:1222/testservice/rest/test/users",
dataType:"jsonp",
succes: function(res) {
alert(ers);
},
error: function(err) {
alert(err);
}
});
However, we were not using jsonp, simple json.
I haven't found a solution for this, only a workaround:
Send the Authorization header using two headers, the standard one and a custom one for IE:
beforeSend: function (jqXHR, settings) {
if (self._hasAuthInfo()) {
jqXHR.setRequestHeader("Authorization", self._makeAuthHeader());
jqXHR.setRequestHeader("IEAuth", self._makeAuthHeader());
}
}
The server side will check both (the second one only if IE and if the standard one is not present)

Resources