how to post data to web service - javascript

Problem Description:- i am trying to call web services of different domain(i.e. Systems are not connected locally with each other) so i am getting error:-"Failed to load https://sap.atlassian.net/: Response for preflight is invalid (redirect)"
var username = "pra#sap.com";
var password = "Sa8";
$.ajax({
type: 'POST',
data: data1,
url: 'https://sap.atlassian.net',
dataType: 'json',
contentType: "application/json",
crossDomain: true,
ProcessData: true,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "POST, GET, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "accept, X-Custom-Header, x-requested-with, X-Auth-Token, Content-Type"
},
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Atlassian-Token", "no-check");
xhr.setRequestHeader('Authorization', "Basic" + btoa(username + ":" + password));
},
success: function(data) {
console.log("success");
},
error: function(e) {
console.log(e);
}
});

First, you might need to double-check URL. There must be some relative URL as well.
This is related to preflight. See https://www.gyanblog.com/gyan/39-explaining-issue-response-preflight-request-doesnt-pass-access-control-check
Can you post detailed stacktrace?
PS: Its always bad practice of putting your username/password openly. You should immediately change your password!

Related

How to fill out a Post Request for a Direct Login authorization in Jquery

I having a question about a post request authorization.
I need to make a request with the following data to get a token.
POST /my/logins/direct HTTP/1.1
Authorization: DirectLogin username="aaaaa", password="686876", consumer_key="GET-YOUR-OWN-API-KEY-FROM-THE-OBP"
Content-Type: application/json
Cookie: JSESSIONID=7h1ssu6d7j151u08p37a6tsx1
Host: 127.0.0.1:8080
Connection: close
User-Agent: Paw/2.3.3 (Macintosh; OS X/10.11.3) GCDHTTPRequest
Content-Length: 0
I have some node.js code.
$.ajax({
url: "https://apisandbox.openbankproject.com/my/logins/direct",
method: "POST",
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
cache: false,
beforeSend: function (xhr) {
/* Authorization header */
xhr.setRequestHeader("Authorization", DirectLogin username="ssmsskan",
password="passs",
consumer_key="wbr3y4vddddddddfffgmcaxxdj2hxok5xt");
xhr.setRequestHeader("X-Mobile", "false");
},
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
I know that the problem is in lin
xhr.setRequestHeader("Authorization", DirectLogin username="aaaaaa",
password="pass",
consumer_key="wbr3y4vcekbcvukgbkbsoandsapjjjjdj2hxok5xt");
But I do not know how to put my DirectLogin information on xhr.setRequestHeader
Thaks
Seems like a simple quote syntax issue. Should be
xhr.setRequestHeader("Authorization", 'DirectLogin username="ssmsskan",
password="passs",
consumer_key="wbr3y4vddddddddfffgmcaxxdj2hxok5xt"');

ajax cors unknown errors

I am trying to solve the problem of cross-domain, whenever I change my code, it never works and I think there must be something wrong with my ajax code, please check in the code, and give me some advice, thank you.
function login(url,name,password){
console.log("login");
console.log(url);
var tips = document.getElementById('tips');
$.ajax({
url: url,
type:"POST",
headers: {
"Content-Type": "application/json"
},
data:{
"user_code" : name,
"user_key" : password
},
dataType: "json",
// xhrFields: {
// withCredentials: true
// },
success:function(data){
if(data.token == undefined){
console.log(data);
tips.innerHTML = "错误";
}else{
saveToken('token',data.token,1);
saveToken('user_id',data.user_id,1);
checkToken(data.token);
}
},
error: function(msg){
console.log(msg);
console.log("fail");
}
});
}
Append in server response in header field,Below code helps you for resolving the issue,i am using below code in java.You can use any other language also.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin");

How to get headers element in node js

I would like to get headers element in server side with node js I try these two codes in client side:
CODE 1
var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ayI6IjU5Mjg0YjQ0MzNhNjU2MmRlNDI1ZGU5MCIsImlhdCI6MTQ5NjY5NjA1NiwiZXhwIjoyOTkzMzk1NzEyfQ.BQskPVT-h-Io4p3Hqraq2qRmVlp_pWAEw5rnIIEA4vk';
$.ajax({
url: 'YourRestEndPoint',
headers: {
'Authorization':'Basic' + token
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Code 2:
$.ajax({
url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
data: { signature: authHeader },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader(
'Authorization':'Basic' + token);
},
success: function() { alert('Success!' + authHeader); }
});
And here the code server:
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Authorization");
console.log(req.headers['authorization']);
I can't get the token in the server side.
In Code 1, you have 'Authorization' as the property name in your header. However, in your code, you console.log 'authorization'.
Try the same capitalization of both. Let me know if the capital was an error with copying and pasting.

How do I make an XGET request with jQuery? [duplicate]

I am trying to create a basic authentication through the browser, but I can't really get there.
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
The address should be something like:
http://username:password#server.in.local/
I have a form:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
And a script:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
Use the beforeSend callback to add a HTTP header with the authentication information like so:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Thanks for your comment!');
}
});
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
The btoa function Base64 encodes a string.
As others have suggested, you can set the username and password directly in the Ajax call:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
OR use the headers property if you would rather not store your credentials in plain text:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Explanation:
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw#domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
And the JavaScript code is:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
Article that I find useful:
This topic's answers
http://enable-cors.org/server_nginx.html
http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

Use basic authentication with jQuery and Ajax

I am trying to create a basic authentication through the browser, but I can't really get there.
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
The address should be something like:
http://username:password#server.in.local/
I have a form:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
And a script:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
Use the beforeSend callback to add a HTTP header with the authentication information like so:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('Thanks for your comment!');
}
});
Or, simply use the headers property introduced in 1.5:
headers: {"Authorization": "Basic xxxx"}
Reference: jQuery Ajax API
The examples above are a bit confusing, and this is probably the best way:
$.ajaxSetup({
headers: {
'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
}
});
I took the above from a combination of Rico and Yossi's answer.
The btoa function Base64 encodes a string.
As others have suggested, you can set the username and password directly in the Ajax call:
$.ajax({
username: username,
password: password,
// ... other parameters.
});
OR use the headers property if you would rather not store your credentials in plain text:
$.ajax({
headers: {"Authorization": "Basic xxxx"},
// ... other parameters.
});
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
<LimitExcept OPTIONS>
AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "Whatever"
Require valid-user
</LimitExcept>
Header always set Access-Control-Allow-Headers Authorization
Header always set Access-Control-Allow-Credentials true
SetEnvIf Origin "^(.*?)$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Explanation:
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
}
});
There are 3 ways to achieve this as shown below
Method 1:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
headers: {
"Authorization": "Basic " + btoa(uName+":"+passwrd);
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 2:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));
},
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
Method 3:
var uName="abc";
var passwrd="pqr";
$.ajax({
type: '{GET/POST}',
url: '{urlpath}',
username:uName,
password:passwrd,
success : function(data) {
//Success block
},
error: function (xhr,ajaxOptions,throwError){
//Error block
},
});
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw#domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
And the JavaScript code is:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
Article that I find useful:
This topic's answers
http://enable-cors.org/server_nginx.html
http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

Categories