XSRF check failed with jQuery (Jira) - javascript

I'm trying to create an issue but it returns the "XSRF check failed" error.
I'm using the following code:
$.ajax({
async: true,
crossDomain: true,
url: 'https://testejiraloupen.atlassian.net/rest/api/2/issue',
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa('email:pass'),
'Content-Type': 'application/json',
/*'X-Atlassian-Token': 'nocache',*/
'Access-Control-Allow-Origin': '*',
'Access-Control-Alow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Headers': 'x-requested-with, content-type'
},
processData: false,
data: JSON.stringify(issue),
success: function(data) {
console.log('Issue created. Id >>> ' + data.id);
}, error: function(err) {
console.log(err);
}
});
Can anyone help me in this case?

It seems to be a known problem by Atlassian, caused by the User Agent sent by your request.
it's in their knowledge base : "REST API calls with a browser User-Agent header may fail CSRF checks", cf https://confluence.atlassian.com/jirakb/rest-api-calls-with-a-browser-user-agent-header-may-fail-csrf-checks-802591455.html
Another discussion thread here : https://community.atlassian.com/t5/Jira-questions/Jira-7-rest-api-XSRF-check-failed-for-post-issue-with/qaq-p/488706
concludes : "Overwrite the User-Agent String with some dummy value, and it will work"

I have used following header for my rest api calls and it worked.
X-Atlassian-Token: no-check
Here is another wiki regarding From token handling:https://confluence.atlassian.com/display/JIRA043/Form+Token+Handling?_ga=2.108983109.653657921.1530909405-1000252910.1505150128

It helped for me:
Resolution: Since REST API doesn't require a User-Agent header, removing the header works.
from this knowledge base page

Related

How can I get JSON data from URL by using AJAX in javascrript

Here when I trying to print response in browser console. It shows this error
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://script.google.com/macros/s/AKfycbwmqG55tt2d2FcT_WQ3WjCSKmtyFpkOcdprSITn45-4UgVJnzp9/exec?url=http://35.230.52.177:8095/OneSoftTracking/rest/tracking/consignment/AE101632?hostname=aastha-enterprises.com&callback=jQuery1124008693115102408444_1561964934754&_=1561964934755 with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.`
While when I get data in Postman like:
This warning or error showing :
This is my code :
var settings = {
async: true,
crossDomain: true,
crossOrigin: true,
url: "http://35.230.52.177:8095/OneSoftTracking/rest/tracking/consignment/AE101632?hostname=aastha-enterprises.com",
method: "GET",
"headers": {
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"*",
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Credentials' : true,
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "bea2b074-eefc-473e-84d7-b680a07ed7df,dafa4f5c-94af-4efe-967f-75a9fe185a1e",
},
success: function(data) {
console.log("+++++SuCCESS");
console.log(data);
},
error: function(error){
console.log("NOT SUCCEED");
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
You haven't shown us your real code.
The error message clearly shows a callback in the query string which isn't in your URL and shouldn't be added because you haven't said dataType: 'jsonp' in the jQuery ajax configuration.
Your real code is configured to use JSONP.
A JSONP response is a JavaScript program (specifically one which calls a single function with a set of arguments). The response you are getting from the server is an HTML document (the content type is text/html and not application/javascript).
The CORB error is the browser telling you that the response is HTML and not JSONP so it is refusing to try to execute it.
The Postman screenshot shows that you are expecting a JSON (still not JSONP) response (but you aren't getting that either).
You need to either:
Change the server to respond with JSONP
Change the request to ask for the correct data (and possibly also change the server to grant you permission to read it using CORS)
Further reading:
What is JSONP, and why was it created?
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
Notes about your code:
async: true,
This is the default, get rid of it
crossDomain: true,
This is the default for cross origin requests, get rid of it.
crossOrigin: true,
This is the default for cross origin requests, get rid of it.
method: "GET",
This is the default, get rid of it
"Content-Type": "application/json",
You are making a GET request. There is no request body to describe the type of. This is nonsense. Get rid of it.
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Credentials': true,
These are response headers, not request headers. Putting them on the request is nonsense. Get rid of them.
"Accept": "*/*",
The default is almost certainly going to be fine. You probably don't need to override it.
"Cache-Control": "no-cache",
The main config option "cache" is probably a better choice than explicitly setting the header.
"Postman-Token": "bea2b074-eefc-473e-84d7-b680a07ed7df,dafa4f5c-94af-4efe-967f-75a9fe185a1e",
The odds of your server caring about this are remote. You can probably get rid of this.

How do I get CORS Post Request working after suggested fixes?

I know this has been asked before - hear me out, because this is not working for me. This is my AJAX function:
$.ajax({
method: 'POST',
url: "https://somedomain.org",
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
headers: {
"Access-Control-Allow-Origin": "http://www.example.org",
"Access-Control-Allow-Headers": "X-Foo",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
},
data: JSON.stringify(generateCartParams()),
context: document.body,
success: function (response) {
console.log(response);
}
});
However, this is still getting me an error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Am I not configuring the settings right?
Edit: I am, of course, setting url and Access-Control-Allow-Origin to the correct addresses - these are just placeholders for this question.

$.ajax requests with CORS

I'm having troubles with an AJAX request. I was getting the below error:
Error: Access is denied
I tried this jQuery AJAX request:
$.support.cors = true;
$.ajax({
url: 'http://testwebsite.com/test',
type: "GET",
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
headers: {
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'http://testwebsite/test',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true'
},
xhrFields: {
withCredentials: true
},
success: function(data) {
alert("Data from Server" + JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert("You can not send Cross Domain AJAX requests: " + errorThrown);
}
});
Can anyone kindly let me know what I am missing. Thanks in advance.
As rory-mccrossan mentioned in a comment, CORS protection is designed so that a website cannot directly access the content of another website (in a browser) unless the website being accessed agrees to it.
It would completely ruin the point of CORS if a site just has to send some headers in order to circumvent the defence
Instead, you will need to use a CORS proxy. It's a server that when given a request like yourCORSproxy.example.com/http://testwebsite/test would load the page and return it, but with CORS allowed (like a normal proxy but with CORS enabled).
One of these CORS proxies is https://crossorigin.me, but at the time of writing this it is down. It might be more stable if you simply create your own proxy.
tl;dr: testsite.test should be sending the headers on its response. You should not be sending the headers on your request.

JSON.parse empty response in Ember

In my Ember project, I use the following code to get a JSON response from my back-end:
Ember.$.getJSON(
mybackendurl.foo/mybarroute,
function (data) {
console.log(data);
});
And there, I get the following error message: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.
My back-end is written in PHP using Symfony, and VoryxRESTGeneratorBundle to send JSON. When I visit http://mybackendurl.foo/mybarroute on my browser, I get a nice JSON response:
{
"links":
[
{
"id": 28,
[...]
}
]
}
It looks like the answer is not correctly detected when using Ember. I'm unsure if the problem comes from back or front-end. How should I fix this?
Additional information:
1) This code in Ember generate a OPTION request, with an empty 200 response:
Ember.$.ajax({
url: http://mybackendurl.foo/mybarroute,
type: 'GET',
contentType: 'application/json'
});
2) I had no more results using chrome
3) Request and response headers
Update
Based on updated Request Response headers, I would guess you are running into Cross-domain problem. Your server runs on PORT 8000, and front-end runs on Port 4200
Either considering going to a JSONP solution or Enable CORS in your server.
Because browser does not support cross domain, you get an error, which ember thinks is a bad JSON.
Here's how you can return JSONP from symfony:
Returning JSONP from Symfony2 controller using AJAX call
Once your server supports a callback parameter in URL, and responds with a callback({your json})
Here's how to use jsonp from Ember:
How do I use the JSONP datatype with Ember Data?
I don't think you've configured CORS on your server, your browser can't receive data from something with a different origin unless CORS is configured correctly.
If you do curl -IX OPTIONS http://whateverisyoururl it should at a minimum send something like this back in the headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
This isn't an ember.js issue, it's a general cross origin request issue.
It turned out to be a configuration problem in nelmio_cors. The thing that got me speding hours is the caching: max_age was set to 3600, so I should have waited 1 hour to see the effect applied.
Setting it to 0 solved my problem.
nelmio_cors:
defaults:
allow_credentials: true
allow_origin: ['*']
allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
allow_methods: ['GET', 'POST', 'PUT', 'OPTIONS', 'PATCH', 'DELETE']
expose_headers: []
max_age: 0
hosts: []
origin_regex: false
paths:
'^/api/':
allow_origin: ['*']
allow_headers: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
allow_methods: ['GET', 'POST', 'PUT', 'OPTIONS', 'PATCH', 'DELETE']
max_age: 0
Try this..
Ember.$.ajax({
url: http://mybackendurl.foo/mybarroute,
type: 'GET',
contentType: 'application/json',
dataType: 'json',
success: function(result){
console.log(result);
}});
and also does your url dont have extensions? i mean something like, mybarroute.php,.json,.js, or .html?

AWSELB Cookie access from Javascript

I having problems to access the "Set-Cookie" header where AWSELB id is stored in order to set it for the subsequent requests.
I thought it was a problem with CORS configuration so i tried:
cors.headers = [
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'origin, authorization, accept, content-type, x-requested-with, X-Auth-Token, Set-Cookie, set-cookie',
'Access-Control-Expose-Headers': 'Set-Cookie, set-cookie'
]
cors.allow.origin.regex = '.*'
cors.expose.headers = 'Set-Cookie, set-cookie'
In the server side.
I can see all those CORS headers in the response, still when i try to getAllResponseHeaders from client side i cannot see "Set-Cookie" neither i can get specific header by name.
I am missing something?
I've check this in both Chrome and Firefox
EDIT1: This is my JS side
$.ajax({
url: url,
type: "POST",
cache: false,
crossDomain: true,
data: JSON.stringify(dataMock),
dataType: "text",
contentType: "text",
success: function(response, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('Set-Cookie')) {
document.cookie = jqXHR.getResponseHeader('Set-Cookie');
}
}
});
};
Cookies are explicitly excluded from getResponseHeader and getAllResponseHeaders:
client . getAllResponseHeaders()
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
client . getAllResponseHeaders()
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
If you want to access them directly from JS then you must change the server so that it duplicates the information in them elsewhere in the response.

Categories