I am attempting to utilize jQuery AJAX to POST dynamic data into JIRA. The idea is to POST to the JIRA REST API via "rest/api/2/issue/".
I believe I have all of my jQuery laid out properly. The issue I'm having trouble getting past is the "XSRF token check" upon execution. Every time I attempt to run my code, it returns "XSRF token check failed" from the server.
I have read about the "X-Atlassian-Token" header. I have that as an allowed header on my jira server config. i.e...
'Header always set Access-Control-Allow-Headers "X-Atlassian-Token, Authorization, Content-Type"'
I have also set the header on my AJAX request. "X-Atlassian-Token": "no-check"
Can someone assist me in getting this to work properly?
JIRA version tested with is 6.4.12.
My current AJAX code is below for review.
$.ajax({
url: "https://my-jira-host.com/rest/api/2/issue/",
type: "POST",
async: false,
headers: {
"X-Atlassian-Token": "nocheck",
"Content-Type": "application/json",
"Authorization": "Basic " + btoa("<username>:<password>")
},
crossDomain: true,
dataType: "json",
data: JSON.stringify({"fields":{"project":{"key":"CLS"},"priority":{"name":"Minor"},"customfield_17125":{"value":"<Department>"},"customfield_17127":"<HOSTNAME>","customfield_17126":{"value":"<Object>"},"issuetype":{"name":"<issue-type>"},"customfield_17128":"dsfgfdsg","summary":"Department | HOSTNAME | Object","description":"sdfgfdg"}}),
success: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("POST was a success!");
console.log("HTTP Error Message: " + XMLHttpRequest.responseText);
console.log("HTTP Status: " + XMLHttpRequest.status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("POST was a failure!");
console.log("HTTP Error Message: " + XMLHttpRequest.responseText);
console.log("HTTP Status: " + XMLHttpRequest.status);
}
});
I should also mention that this code is being sent from client website I created internally. Both client front-end and JIRA host are on the same internal network.
XSRF (Cross Site Request Forgery) is a security feature used by Jira to prevent users from being tricked into submitting malicious data.
If you are using Firefox or Chrome, you may need to set the User-Agent with a dummy value like this:
headers: {
"X-Atlassian-Token": "nocheck",
"Content-Type": "application/json",
"Authorization": "Basic " + btoa("<username>:<password>"),
"User-Agent": "xx"
},
Related
I am having some trouble getting a few things working. I am trying to connect through basic authentication. I am using javascript in my HTML code. I get the following error message: " Failed to load http://**********/connections?********* : Response for preflight is invalid (redirect)" where I have redacted the API endpoint. The code I wrote is the following.
var Key = "something";
var Secret = "something else";
var url = 'http://**********';
$.ajax({
headers: {
'X-******-Key':Key,
'X-**********Secret':Secret,
'Content-Type':'application/x-www-form-urlencoded'
},
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
alert("Success", json);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(Key + ":" + Secret));
},
type: 'GET',
contentType: 'json',
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
hi
</html>
You can substitute the API end points and secret and Key to try the code for a common basic authentication API to try the code. I don't have access to the Server. I know it is still possible to make this work because someone else said they have this working. Can anyone help me with this?
Response for preflight is invalid (redirect)
Your server doesn't handle CORS properly.
Browsers won't let fetch data via ajax if the request is made to an external domain unless the server handles CORS properly and CORS headers are available in the responses.
Please read the article:
https://developer.mozilla.org/en-US/docs/Web/HTTP/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.
I am requesting a video from an API that requires JWT web tokens:
// when the ajax call is done (the tolken is recieved )
getAccessToken.done(function(data) {
var d = JSON.stringify({'fpath': fpath})
// get the download url
var downloadurl = $.ajax({
type: "POST",
url: "https://gcp.inbcu.com/download",
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "JWT " + data.access_token);
},
contentType: 'application/json',
data: d,
success: function(response){
$('#video-source').attr('src', response.url)
$('#myvideo').load()
},
error:function(jqXHR, textStatus, errorThrown) {
console.log("request for download url failed: ", textStatus, errorThrown, jqXHR);
},
dataType: 'json'
});
This ajax call itself is successful (200) and returns the proper values. Mainly it returns a url to set the source of the video.
Problem is, the video src attempts to access the url and doesn't have permission (no jwt token/ authorization). How am I supposed to load the video with the proper permission when loading the src of a video? Is this possible?
As the answer to a similar question explains, this isn't possible. Either you need to do it as an AJAX request, which you previously did, but which was slow, or, you need to add additional methods for the server to accept authentication.
Regarding these auth options, you could add a session cookie that the server can check, or append the token to the video url, like response.url + '?token=' + token.
A service worker would be capitabel of adding the auth token. But that only solves the problem for FF & Blink
I have a problem. I have the Authorization header generated by OAuth Tool in Twitter (I hid value of keys)
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"
And I have a AJAX code:
$.ajax({
url: 'https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4',
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="xxxxxxxxxxxxxxx", oauth_nonce="xxxxxxxxxxxxxxx", oauth_signature="xxxxxxxxxxxxxxx", oauth_signature_method="HMAC-SHA1", oauth_timestamp="xxxxxxxxx", oauth_version="1.0"');
},
dataType: "jsonp",
success: function(data) {
console.log("Success: " + data);
}
},
error: function(data) {
console.log("Error " + data);
}
});
But this code returned error
Object {readyState: 4, status: 404, statusText: "error"}
Here is part of documentation Twitter REST API which I use:
https://dev.twitter.com/rest/reference/get/search/tweets
What is wrong? Any ideas?
Twitter does not support generating the authentication header from a webpage. You must go through the "handshake" using their site to authenticate and redirecting back to your webpage.
If you want to avoid this and keep your oauth keys locally, you will need to build a server which can authenticate using stored keys. Then your webpage will make Twitter requests via your server.
My problem is "simple". I'm developing a hybrid Android application that makes HTTP requests via Jquery Ajax.
The problem is that when my requests gets failed(Server returns 401/403 ...etc), Jquery fires only HTTP 404 error that is not correct.
I'm making HTTP post requests like that:
var request = $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: obj,
cache: false,
contentType : 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
success: function(data){
// Success
},
error: function(request, status, errorThrown){
console.log("call Login ajax failed with error, status:" + status + " errorThrown:" + errorThrown);
console.log("call Login ajax failed with errorCode : " + request.status);
}
The strange thing is that when i run my project as DynamicWeb project in my browser at my PC and in the url use my ip address the jquery fires the correct error events, but when i use "localhost" in the url, the jquery act as in the android devices, fires only 404 event.
I tried to change jquery libary to a newest version 2.1.1 but this doesn't help.
PS. I'm using jquery 2.0.2...
You'll need to set the header of the response to Content-type: application/json.
Before you echo the json. Or you could set the type of the ajax call to text, html.
Also it is recommended to chain your callback functions with jquery like so
$.ajax({
url: url,
headers: { "Accept-Encoding" : "gzip" }, // Use the response seen in sniffer
type: 'POST',
dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
})
.done(function(response) {
console.log("success");
console.log(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
The problem for me was that server doesn't allow Cross-domain requests. So i must set "Access-Control-Allow-Origin:", "*" header in responses from my server and everything will be ok...