I'm trying to make an ajax call to service, my service api expects a Request Header for Authorization to give the response
Here is my JS code
var settings = {
url: "http://localhost:8080/codebluet-war/service/codeblue/facility",
method: "GET",
headers: {
"Authorization": "oauthtoken"",
}
}
$.ajax(settings).done(function (response) {
console.log(response)
});
I have added the Authorization headers in my code but still I'm getting 401 unauthorized request error.is there any other thing that I need to add in my settings?
If you are using OAuth 2.0 you should prefix the token value with Bearer word:
headers: {
"Authorization": "Bearer yourTokenValue",
}
With OAuth 1.0, it's a little bit more complicated since you need to send a set of parameters instead of a single token. Therefore, you may want to consider using a jQuery compatible OAuth library for this purpose.
Related
as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.
In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks
Problem
When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.
As far as i have understood the cause of this error, its because of cookies not sent with the request.
To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.
Question
Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?
Code
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
When using fetch()/AJAX with csurf, you need to pass the CSRF token as a request header:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});
Hello I am using this method to read this api it giving CORS error. I have added CORS plugin with chrome then also it is not coming. Please let me know how to solve these to error.
text:
function NoCors() {
debugger;
var uName = "*****";
var passwrd = "*****";
document.write("Enter1");
var url = 'http://219.90.67.163:8207/api/Info/getgismeterdata'
$.ajax({
type: 'GET',
url: url,
crossDomain: true,
//Access-Control-Allow-Credentials: true,
contentType: 'json',
datatype: "application/json",
headers: {
"Authorization": "Basic QXBpVXNlcjpBcGlQYXNz",
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic " + btoa(uName + ":" + passwrd));
},
success: function (data) {
debugger;
console.log("data")
//Success block
},
error: function (xhr, ajaxOptions, throwError) {
//Error block
},
});
}
error in console:
1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
2. Access to XMLHttpRequest at 'http://219.90.67.163:8207/api/Info/getgismeterdata' from origin 'http://localhost:50362' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Before sending the GET request to server, browser automatically send and preflight OPTIONS request, and your server doesn't allow this method. You need to enable OPTIONS method support in your server side (219.90.67.163)
Are you use Bearer Token Authentication?
requst headers try this
headers: {
"Authorization": "Bearer QXBpVXNlcjpBcGlQYXNz",
},
You must setting CORS in Web API
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
The CORS plugin you are using only works for Simple Requests.
Since you are setting an Authorization header you are making a Preflighted Request which your plugin cannot handle.
You need a different approach to handling the Same Origin Policy. Ideally, that would be proper support for CORS on the server you are making the HTTP request to but some other options are listed at the end of this answer.
I'm looking at the following documentation for vue-resource that describes how to set up configuration: https://github.com/vuejs/vue-resource/blob/master/docs/config.md
It says to set your headers with a common authorization value:
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
I am guessing this "Basic YXBpOnBhc3N3b3Jk" value is just an example, but what is this value for, and what should one use instead of it?
On the same page, I also see a setting for "root":
Vue.http.options.root = '/root';
I understand this to mean the web URL for the web app. However, why does vue-resource need me to tell it this value? What does it use it for?
By adding headers to the Vue.http.headers.common object you are telling vue-resource to add these headers in every request.
You can also add headers to each request:
http({
url: '/someUrl',
method: 'GET',
headers: {
Authorization: 'Basic YXBpOnBhc3N3b3Jk'
}
})
About the value for the Authorization header in the example: It is a base64-encoded string with username/password.
window.atob('YXBpOnBhc3N3b3Jk') // => "api:password"
If you need to use basic authentication when using vue-resource, you should provide your own username/password.
Note that everyone who is using you application can view the username/password.
See https://en.wikipedia.org/wiki/Basic_access_authentication for more information about basic authentiaction.
The root-property could be the main endpoint to your REST-service.
Instead of:
http({
url: 'http://api.domain.com/v1/someRoute'
});
You could set the root endpoint with:
Vue.http.options.root = 'http://api.domain.com/v1'
// will call http://api.domain.com/v1/someRoute
http({
url: '/someRoute'
});
If you want set header auth in global way use the inceptor
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abcd' //Base64
request.headers['Accept'] = 'application/json'
next()
});
and use option credentials:
Vue.http.options.credentials = true;
I'm looking for a code example creating a REST POST request with JQuery on Neo4j 2.2.x Transactional Cypher HTTP endpoint with new REST API Authentication and Authorization parameters.
Before Neo4j 2.2 version I used the Legacy Cypher HTTP endpoint (which is deprecated) to execute Cypher queries with the following code:
$.post("http://localhost:7474/db/data/transaction/commit",
{
"query": query,
"params": {}
}, "json")...
But I would like to move to 2.2 and use the transactional endpoint with user authentication parameters.
I can't find the right headers and parameters combination to use to create such a request. That's why I'm looking for a code example.
Best would be an example using a cross domain request but an example on same domain would be helpful too.
For authentication you need to supply an additional HTTP header to your request:
Authorization: Basic realm="Neo4j" <base64>
where <base64> is the base64 encoded string of username:password.
Not being a jquery ninja, but I guess the most simple way is to set the authorization header using ajax defaults:
$.ajaxSetup({
headers: { "Authorization": 'Basic realm="Neo4j' <base64>'}
});
When this default has been applied your $.post above should work.
The issue has been fixed in 2.2.0-RC01 and I can use transactional Cypher HTTP endpoint with authentication using the following example code:
$.ajaxSetup({
headers: {
// Add authorization header in all ajax requests
// bmVvNGo6cGFzc3dvcmQ= is "password" base64 encoded
"Authorization": "Basic bmVvNGo6cGFzc3dvcmQ="
}
});
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit ",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({"statements": [{"statement": "MATCH (n) RETURN n LIMIT 10"}]}),
success: function (data, textStatus, jqXHR) {
// use result data...
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors
}
});
Authorization means that the browser will send a preflight OPTIONS request which does not embed authorization headers.
This is most known as CORS.
Currently the Neo4j server do not reply to the OPTIONS request with the appropriate Access-Control-Allow-Headers.
This feature has been implemented in the source code and will be shipped with the GA release which I hope will come out this week.