I want to run a Jenkis job that requires login from a web page (outside of jenkins) using ajax
currenly i have to have another browser tab with jenkins open (and authenticated) in order for the job to run from my web page
iv'e tried different approaches to sending the authentication info with ajax
this is what i currently have:
$.ajax({
type: "POST",
url: "http://myjenkins/job/job_name/buildWithParameters",
dataType: 'jsonp',
data: $("#myForm").serialize(),
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "username:password");
},
success: function(data) {
},
complete: function(xhr, statusText){
}
});
(there's some more HTML code that receives parameters from a form)
if i have an open tab with jenkins authenticated this runs fine, but if i don't i get a "430 forbidden" responce from jenkins.
the "xhr.setRequestHeader("Authorization", "username:password");" is just my latest attempt...
any input is welcome!
This worked for me, thanks a lot, just to expand, it worked because As per RFC 1945, the Authorization header value should contain the username:password as encoded (base64) string, which would result in something like the following header:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
example:
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:token"));
}
beforeSend: function (xhr) {
xhr.withCredentials = true;
data: $("[name='parameters']").serialize()
xhr.setRequestHeader("Authorization", "Basic " + btoa("test:d8db6ae61f03219c52042638488e9744"));
},
works for me
Related
I can open an API url in chrome by going to some address like:
http://some-path-to-server.com/myapi/
and it asks for a user/pw
After logging in I can see the json response. Question is how can I get that json via $.getJSON api call in my localhost server? Or how I can dig it out that extra params I need to send in my getJSON call.
Just call $.getJSON api in your javascript.
function getJson(){
$.getJSON("your url", function(data){
alert("JSON Data: " + JSON.stringify(data));
});
}
Upd: You can add authorization info in headers like below code. Or using beforeSend function to add extra info to headers.
$.ajax({
type: "get",
url: "your url",
dataType: "json",
headers: {
"Authorization": "Bearer 5c530532-f39c-4f22-b48c-e226f8d08405"
},
success: function(result) {
console.log(result);
}
})
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 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...
On site1.domain.com I am running a greasemonkey script that takes in user credentials to authenticate to site2.domain.com and pull the entire page and parse out a server generated token that is needed to complete the rest of the script running on site1.domain.com and then make another URL GET to site2.domain.com.
xmlhttp.open("GET", url, false, username, password );
is the call I'm attempting but I'm receiving the error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied". I looked around and I understand that there are complications with this type of functionality but I haven't figured out what I need to do in this situation.
EDIT: Tried this using verisons of the code below but receiving Cross-domain error for any datatype other than jsonp but with jsonp I recieve "htmlString is undefined". I also tried defining the return value as a String and in that case I received "6" (without any manipulation).
var htmlString = getPage(url,username, password);
var index = htmlString.indexOf("Token");
//some other code that parses out just the token, shown as "finalString" in the end
$("#logMessage").text (finalString);
function getPage(url, username, password) {
return $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', btoa(username + ":" + password));
}
}).responseText;
}