I am trying to send a DELETE request to a tomcat server using AJAX.
I want the request to use a basic auth. I can't really get there if the password contains special characters.
The configuration of the system is:
jquery 1.10.2
tomcat 7.0.47
Before asking I try to follow what I found in:
How to use Basic Auth with jQuery and AJAX?
How can you encode a string to Base64 in JavaScript?
Javascript Ajax call using password with special characters
The Tomcat configuration is:
</tomcat-users>
<role rolename="authUser"/>
<user username="username" password="password" roles="authUser"/>
</tomcat-users>
I made an ajax request using jquery
$.ajax({
type: "DELETE",
url: "http://localhost:8080/TestAuthentication",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
username: "username",
password: "password",
success: function(){
alert("Data Deleted");
}
});
With this configuration everything works.
If I put special characters in the configuration file of tomcat I'm no more able to make correct request.
</tomcat-users>
<role rolename="authUser"/>
<user username="username" password="AeHm#%%9Rt\'JzX^|A'N" roles="authUser"/>
</tomcat-users>
I try with two ajax settings
$.ajax({
type: "DELETE",
url: "http://localhost:8080/TestAuthentication",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
username: "username",
password: "AeHm#%%9Rt\'JzX^|A'N",
success: function(){
alert("Data Deleted");
}
});
$.ajax({
type: "DELETE",
url: "http://localhost:8080/TestAuthentication",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
username: encodeURIComponent("username"),
password: encodeURIComponent("AeHm#%%9Rt\'JzX^|A'N"),
success: function(){
alert("Data Deleted");
}
});
with this two configurations I see the same request.
So I try a more older approach
$.ajax({
type: "DELETE",
url: "http://localhost:8080/TestAuthentication",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authentication", "Basic " + btoa(unescape(encodeURIComponent("username" + ":" + "AeHm#%%9Rt\'JzX^|A'N"))));
xhr.setRequestHeader("Authorization", "Basic " + btoa(unescape(encodeURIComponent("username" + ":" + "AeHm#%%9Rt\'JzX^|A'N"))));
},
success: function(){
alert("Data Deleted");
}
});
With this request I always get the error: 401 (Unauthorized)
But usign a c# client I'm able to authenticate the request:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(#"http://localhost:8080/TestAuthentication");
request.Credentials = new NetworkCredential("username", #"AeHm#%%9Rt\'JzX^|A'N");
....
And I'm also able to access to URL if I put "username" and "AeHm#%%9Rt\'JzX^|A'N" on alert show me from the browser.
So it seems to be a problem of the request I made.
Please, could someone help me?
Finally I have undestand the problem was: the escape
Writing:
AeHm#%%9Rt\'JzX^|A'N
wrong output: AeHm#%%9Rt'JzX^|A'N =>so I lost the "\" character
Writing the password escaping the "\" character
AeHm#%%9Rt\\'JzX^|A'N
correct output: AeHm#%%9Rt\'JzX^|A'N
Here the working code:
$.ajax({
type: "DELETE",
url: "http://localhost:8080/TestAuthentication",
beforeSend: function(xhr) {
//May need to use "Authorization" instead
xhr.setRequestHeader("Authentication", "Basic " + btoa(unescape(encodeURIComponent("username" + ":" + "AeHm#%%9Rt\\'JzX^|A'N"))));
xhr.setRequestHeader("Authorization", "Basic " + btoa(unescape(encodeURIComponent("username" + ":" + "AeHm#%%9Rt\\'JzX^|A'N"))));
},
success: function(){
alert("Data Deleted");
}
});
Related
I am trying to send a request using ajax to a server which is protected by basic authentication with the following code:
$('document').ready(function(){
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa('myusername' + ":" + 'mypassword'));
},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
});
So I provide the credentials in the beforeSend so my expectation would be that there would be no credential popup from the browser since I already provided the credentials but unfortunately when i run this code I get the popup to enter my credentials. I want to the code to provide these credentials.
Similar to this question, example using headers:
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
headers: {"Authorization": "Basic " + btoa('myusername' + ":" + 'mypassword')},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
I am trying to append extra information to the jsonrequest that is sent from my application to DialogFlow. I am aware of the possibility to send data calling an intent by triggering its event from Sending Parameters in a Query Request, and I am using that method already for other functionality.
Basically, I am trying to add a value with the userID, and I need to retrieve that value in DialogFlow. I am keepeing track of the session in php, so I am using phpto get ID value. I have tried to do the following in the ajaxrequest:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100"
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
And this one as well:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100",
parameters: {
userId: "100"
}
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
I need that value in the request to process some data in the back-end based on it. If anyone knows how to do it, or has suggestions for a better approach that would be much appreciated.
There are discussion posts related to this in the DialogFlow Forums, but there is still no resolution. The feature might not be available, or it is not documented Link 1, Link 2, Link 3.
I solved this issue with the help of #Svetlana from Dialogflow. The original post is Here, and here is an example from a JavaScript application with back-end in Node.js:
You would format your request like:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({originalRequest: {data: {exampleMessage: 'Test'}}, query: text, lang: 'en', sessionId: 'somerandomthing'}),
success: function (data) {
},
error: function () {
setResponse("Internal Server Error");
}
});
and you would access the value in the webhook with:
var exampleMessage = req.body.originalRequest.data.exampleMessage;
or
var exampleMessage = req.body.originalRequest.data['exampleMessage'];
Hope this helps.
I've been reading a lot of questions about this error, but just can't seem to get around it (it's incredible how many questions can be found on the web on this topic!!). Let me be straight:
test.asmx
'Simple POST (obviously with parameters)
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
Dim x
End Function
'Simple GET - no parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
return "ok ;>D"
End Function
'GET with parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
return Valor
End Function
Trying it out in js console window:
obj = { Valor: "x" }
$.ajax({
type: "POST",
url: "test.asmx/TestarPost",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success!
$.ajax({
type: "GET",
url: "ServerSide.asmx/Testar",
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success! Returns correctly data in JSON format
$.ajax({
type: "GET",
url: "test.asmx/TestarGet",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Fails! Doing the same as in Post
The message error is "Invalid web service call, missing value for parameter: \u0027Valor\u0027." Also fails if I send object literal ("Invalide JSON primitive"). However, if I access URL .../ServerSide.asmx/TestarGet?Valor=x, it returns "opa" (maybe a clue?)
What I don't get (pardon the pun) is why, since it's the same as in POST. Maybe because the POST isn't affecting anything and I can't see the result (but it returns no errors, at least).
My goal is to create a function serverSide(asmxMethod, obj) to make a generalized bridge between client and server functions.
I've found a solution (but not an answer). According to a friend, GET doesn't accept json parameters. Unfortunately, even if I send dataType: "text" it fails.
The solution is to use always POST. POST is also able to return data (didn't know that). So with the POST example I can send and receive data in json format without a problem.
I have searched the forums here for a while and am still at a loss. I am doing Basic Authentication with a predefined username and password.
I know that the username and password are correct because I can directly log in.
I have tried passing a "header", "username", "password" and as you see below using "beforeSend".
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); },
error: function (){
alert('cant connect');
},
success: function (){
alert('connected');
}
});
I think you need to use the headers parameter to pass authentication. Try this:
$.ajax({
type: "GET",
url: "https://vcc-na10.8x8.com/api/stats/groups.xml",
datatype: "xml",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
error: function() {
alert('cant connect');
},
success: function() {
alert('connected');
}
});
Try sending the username and password directly in the ajax config.
$.ajax({
type: "GET",
username: username,
password: password,
...
I need to get xml document from a server, then client signs it and sends back to server.
At server side I have web method which saves document:
[WebMethod]
public static void SaveSignedDocument(string SignedData)
{
SignedCms signedCms = new SignedCms();
....
}
Then, I get document from a server and after success receive it I make client to sign it and send back. Here is Javascript
// get xml to sign
$.ajax({
type: "POST",
url: "Default.aspx/GetXMLReceipt",
data: "{'ITN': " + ITN + " }",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
// xml file was got
var xmlString = xmlToString(xmlData);
// Sign data
var SignedData = SignData(xmlString);
// Send it to server
$.ajax({
url: 'Default.aspx/SaveSignedDocument',
data: "{ 'SignedData': '" + SignedData + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){
alert('Document was successfully sent!');
}
error: function (data, status, jqXHR) {
alert('Send signed data failed - ' + jqXHR);
}
});
},
error: function (data, status, jqXHR) {
alert('Get data failed - ' + jqXHR);
}
});
The problem is that none of the alert at second requests ever fire. If I change request to synchronous everything is ok but why it does not work like written above? The server receives nothing and if we look to network traffic I see that request was interrupted. Why?
Encode your data properly, do not use any string concatenations. Here's the correct way:
data: JSON.stringify({ ITN: ITN }),
and on your second AJAX request:
data: JSON.stringify({ SignedData: SignedData })
The JSON.stringify method will ensure that you are sending valid JSON to your server by properly encoding the argument.