axios delete method gives 403 - javascript

I am calling delete method from my node-js application.
Its working fine from Postman but giving me 403 while calling this API
from code.
Below is my sample code snippet:
const instance = axios.create();
instance.interceptors.request.use((config) => {
config.baseURL = 'https://test-dev.com/api/portfolio'
config.headers = { 'Authorization' : 'Bearer ' + <TOKEN>}
return config;
});
instance.delete('/admin?users=<VALUE>').then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
EDIT:
Response (Coming from spring security APP):
Could not verify the provided CSRF token because your session was not found
I thought this is already handled by axios.
How can i pass this value in headers while calling delete method?
Any help?

You could either:
1 - Use the withCredentials property:
withCredentials: true
so:
axios.delete({
url: 'https://test-dev.com/api/portfolio/admin?users=' + <VALUE>,
headers: { 'Authorization' : 'Bearer ' + <TOKEN>},
withCredentials: true
}).then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
The XMLHttpRequest.withCredentials property is a Boolean that
indicates whether or not cross-site Access-Control requests should be
made using credentials such as cookies, authorization headers or TLS
client certificates. Setting withCredentials has no effect on
same-site requests.
2 - Set CSRF headers
Either:
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
or
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': 'your token here'}
or just:
headers: {'X-Requested-With': 'XMLHttpRequest'}
3 - Disable at own risk and if possible
Have a look at this article

So after a number of tries, I found it working.
Please follow the order sequence it's very important else it won't work
axios.delete(
URL,
{headers: {
Authorization: authorizationToken
},
data:{
source:source
}}
);

Related

I cannot request an Oauth 2.0 token in javascript

I am making a request for getting an access token with Oauth 2.0, in javascript. The docs of the API use the request module (deprecated), so I am searching for an alternative. I tried with fetch and axios, but none of them seem to be working.
You can read this from the docs.
If i make the request with axios (code) it returns this error,
while if I use fetch (code) this it the result.
At least fetch makes the call successfully, but I have the impression that he cannot pass the auth parameter, because the error is caused beacause of this.
May someone help me? I appreciate it a lot.
You can use fetch or axios instead of request, but they use different options attributes, compared to request.
With axios, it is
const options = {
method: 'POST',
auth: {
username: client.id,
password: client.secret
},
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: 'grant_type=client_credentials&scope=basic'
};
instead.
With fetch, it is
const options = {
method: 'POST',
headers: {
authorization: "Basic " + Buffer.from(client.id + ":" + client.secret).toString("base64"),
'content-type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&scope=basic'
};
You can use axios this way:
axios.interceptors.request.use(function (config) {
// Do something before request is sent
config[Authentiaction] = "Bearer" + token
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
I think this can help.

401 Unauthorized REST API in lightning web component salesforce

I'm trying to execute query using REST API, in a lightning web component.
the request in Postman returning result with success (enabling Follow Authorization header)
but in the JavaScript in lightning web component it returns 401 Unauthorized
the code in the java script is a follow :
let sessionId = 'tokken';
let baseUrl = window.location.origin;
let header = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + sessionId,
};
if (sessionId) {
let options = {
method: "GET",
mode: 'no-cors',
redirect: 'follow',
headers: header,
};
fetch(baseUrl + '/services/data/v50.0/query/?q=SELECT+name+from+Account', options).then((response) => {
console.log(JSON.stringify(response));
if (!response.ok) {
// throw Error(JSON.stringify(response));
} else {
return response.json();
}
}).then((repos) => {
console.log(repos, repos);
});
}
am I missing something ?
Since you can not pass the value Authorization to no-cors mode, you will need to add CORS configuration in your SalesForce as safe endpoint where they let you make a call.
You can not send Authorization header with "no-cors" mode.
mode: "no-cors"only allows a limited set of headers in the request:
Accept
Accept-Language
Content-Language
Content-Type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain

cannot convert auth token to string

I need to request POST method to authorize and set current location of user in my react-native application. As authorization header,I add token which I get before from API and saved it to the state. However, when I make request, I get error message of auth header empty. Whereas, when I console.log the token, it prints correctly. I guess the issue is something about the type of token. I tried to convert it to string, but nothing changed.
By the way, I checked request with static token - copy&pasted token instead of this.state.token and it worked perfectly, so it is clear that I live problem with converting the token.
Here is the code that I make request.
console.log("AUTH TOKEN: ", this.state.token);
var Url = "https://-----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.state.token
},
body: JSON.stringify({'latitude': this.state.location.coords.latitude.toString(), 'longitude': this.state.location.coords.longitude.toString()})
})
// .then((response) => response.json())
.then((response) => {
console.log(response);
})
.done();
here is the result of request on console.
Has anyone lived such issue before?

When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code

in my React app, I have the following API POST to allow the user to edit their profile (name and image).
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
The problem with the above is the header with the Authorization token is not being sent in the POST...
How can I get the Authorization header to be send in the fetch request above?
FYI, for non-multipart forms, the authorization token is sent successfully like so:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
You can’t use no-cors mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
To append a name/value pair to a Headers object (headers), run these steps:
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.
In that algorithm, return equates to “return without adding that header to the Headers object”.
Authorization isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use no-cors mode for a request. Same for Content-Type: application/json.
If the reason you’re trying to use no-cors mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, no-cors mode isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
By using below code you can make a fetch request with Authorization or bearer
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));

Basic authentication (or any authentication) with fetch

Couldn't find any documentation on this, so before I dig deep in code does anyone out there know how to use basic authentication when making a REST request using 'fetch' (https://github.com/github/fetch).
Just tried the following line, but the header was not set in the request:
fetch('http://localhost:8080/timeEntry', {
mode: 'no-cors',
headers: { 'Authorization': 'Basic YW5kcmVhczpzZWxlbndhbGw=' }
})
.then(checkStatus)
.then(parseJSON)
.then(function(activities) {
console.log('request succeeded with JSON response', data);
dispatch(activitiesFetched(activities, null));
}).catch(function(error) {
console.log('request failed', error);
dispatch(activitiesFetched(null, error));
});
The username and password is my own first and last name, using curl it works.
If I put { 'Accept' : 'application/test' } Accept is set, just not Authorization... strange.
Just for me to able to continue I added credentials: 'include' which makes the browser to prompt for username and password which is used for communicationg with the REST backend. Just for testing, will use OAuth further on.
fetch('http://localhost:8080/timeEntry', {
mode: 'no-cors',
credentials: 'include'
})
.then(checkStatus)
.then(parseJSON)
.then(function(activities) {
console.log('request succeeded with JSON response', data);
dispatch(activitiesFetched(activities, null));
}).catch(function(error) {
console.log('request failed', error);
dispatch(activitiesFetched(null, error));
});
no-cors mode prevents the headers from being anything other than simple headers.
"Authorization" header doesn't fit to simple headers. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
Note that if you use fetch with Authorization header you will NOT establish a session. You will have to manually add that header for every request. Navigating to secured path would also not be possible.
So to make this work You should pre-authenticate with XMLHttpRequest. You can do this like so:
var authUrl = location.origin + '/secured-path/';
var http = new XMLHttpRequest();
http.open("get", authUrl, false, login, pass);
http.send("");
if (http.status == 200) {
//location.href = authUrl;
} else {
alert("⚠️ Authentication failed.");
}
Note that above is synchronous so you don't need a callback here.
So after doing this you can use fetch without headers e.g. this request should be successful:
fetch(authUrl, {
method: 'get',
}).then(function(response) {
console.log(response);
});
Since it looks like the library you are using is a polyfill for Fetch API, I'm going to work off of the assumption that the syntax should carry through as well.
The samples I found on Mozilla's page indicate that the fetch method signature is fetch('API_ENDPOINT', OBJECT) where object looks like:
myHeaders = new Headers({
"Authorization": "Basic YW5kcmVhczpzZWxlbndhbGw="
});
var obj = {
method: 'GET',
headers: myHeaders
})
So the method becomes:
fetch('http://localhost:8080/timeEntry', obj)
.then(checkStatus)
.then(parseJSON)...
I have not tested this code, but it seems consistent with what I was able to find. Hope this points you in the right direction.

Categories