I'm looking for example of fetch() method to call secured API (I use Azure AD B2C)
To be specific I I don't know how should my headers look like.
Calling API using Postman with authorization works.
My API is hosted on localhost:44320 I didn't deploy it.
In React I use 'react-azure-adb2c' library and it also works. I can log in and after that I'm getting token with all claims which I need.
var token = auth.getToken(); //here is the token which is correct
fetch("https://localhost:44320/api/worker/", {
method: "GET",
headers: {
Authorization: token,
Accept: "application/json",
Host: "localhost:44320"
}
})
.then(res => res.json())
.then(json => this.setState({ listOfWorkers: json.results }));
}
You specify the header as Authorization: Bearer token-value-here.
So Authorization: 'Bearer ' + token in your case.
Related
I want to get a list of all the products from my BigCommerce store using an API call. This is the code I have used:
fetch("https://api.bigcommerce.com/stores/##########/v3/catalog/products", {
method: "GET",
mode: "no-cors",
"X-Auth-Token": "###############################",
"Content-Type": "application/json",
Accept: "application/json",
})
.then((res) => res.json())
.then((json) => console.log(json));
I have used the correct store hash and access token but I get this error:
I understand this is a very basic question but I would like some help as I am stuck.
Using the rest client extension and the same credentials, I am able to get the list of products:
I believe you're missing the headers object as well as missing quotes around Accept. Also, if you're running this on the client side, this will not work, as you 'd need make a server side API request to get all products. To do so, you will need to make the API request to some middleware application.
In addition to making the request on the server side, try modifying it a bit to look like this:
fetch(`url`,{
method: 'GET',
headers: {
'X-Auth-Token': '<token>',
'Content-Type': 'application/json',
'Accept': `application/json`
}
})
.then((res) => res.json())
.then((json) => console.log(json));
In a bit of a pickle at the moment , I could do a postman request like that and I get my data response back :
URL : https://hiddenurlforexample.com
Authorization : Bearer XXXXXXXX-XXXX-XXXX-XXXX
When I do it on Axios on my website though I get a 401 CORS error. Any idea what the difference is ? This is how my axios request looks like :
axios
.request({
url: 'test/url',
method: 'get',
baseURL: 'https://hiddenurlforexample.com',
headers: {
"Access-Control-Allow-Origin" : "*",
"Content-type": "Application/json",
"Authorization": "Bearer XXXXXXXX-XXXX-XXXX-XXXX"
}
})
.then(response => {
console.log(response.data)
})
.catch(function (error) {
console.log(error)
})
I am a Frontend Developer, I have been told that there was nothing to do in the backend .
What Chris G said, and next to that Postman ignores the CORS validation because it is a dev tool.
Your backend server should return the correct CORS headers. While developing you could go with a wildcard for the CORS headers but it's highly recommended to add the specific domain you're calling the backend from (i.e. the domain of your website).
Also note that the CORS headers are returned via an OPTIONS call, again, your backend should support that. What backend are you running?
I am trying to use the Basic Authorization method that accepts username and password. I am working in React, using a fetch. It does not seem to work. It sends status 401 Unauthorized. I've no two-factor authentication. And yes, I have used PAT but I want to authenticate using username:password method. Kindly look at the code:
fetch("https://api.github.com/user", {
method: "GET",
headers: {
Authorization: `Basic ${btoa(`${username}:${password}`)}`,
"Content-Length": 0,
},
}).then((response) => response.status);
I'm trying to do a authorization request with Github Api, passing the username and password.
But it's not working and i'm getting 401 status code.
In the Documentation there's a part saying
To use Basic Authentication with the GitHub API, simply send the username and password associated with the account.
That's my code:
this.api
.post('/user', { username: 'Example', password: '1234' })
.then(res => resolve(res.data))
.catch(err => reject(err));
Not sure if you aim to use the Basic Authentication provided by Github API. If that's the case I think you should use the Axios auth header:
axios.get('https://example.com', {
auth: { user: "username", password: "password" }
});
Here's what Axios docs say:
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
There's another way to manually set the authorization header like this:
axios.get('https://example.com/', {
headers: {
Authorization: 'Basic ' + Base64.encode('username' + ':' + 'password');
}
})
And the last note is that deprecation is coming:
Deprecation Notice: GitHub will discontinue password authentication to the API. You must now authenticate to the GitHub API with an API token, such as an OAuth access token, GitHub App installation access token, or personal access token, depending on what you need to do with the token.
Consider using tokens instead of username and password.
Note that if your account has activated 2FA (two-factor authentication), then you would need to use a PAT (Personal Access Token) as your password.
curl --header 'Authorization: token INSERTACCESSTOKENHERE'
--header 'Accept: application/vnd.github.v3.raw'
--remote-name
--location https://api.github.com/...
See "Passing headers with axios POST request"
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/vnd.github.v3.raw',
'Authorization': 'token INSERTACCESSTOKENHERE'
}
axios.post(url, data, {
headers: headers
})
.then((response) => {
dispatch({
type: yourEvent,
data: response.data[0]
})
})
.catch((error) => {
dispatch({
type: yourError
})
})
Basic authentication requires you to add a header to the ajax request which gets send to the GitHub API. This is already answered in use-basic-authentication-with-jquery-and-ajax.
How can I send an authentication header with a token via axios.js?
I have tried a few things without success, for example:
const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });
Gives me this error:
XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.
I have managed to get it work by setting global default, but I'm guessing this is not the best idea for a single request:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Update :
Cole's answer helped me find the problem. I am using django-cors-headers middleware which already handles authorization header by default.
But I was able to understand the error message and fixed an error in my axios request code, which should look like this
return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });
On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.
In your case, you're trying to send an Authorization header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.
Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.
tl;dr - If you'd like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.
This has worked for me:
let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Rather than adding it to every request, you can just add it as a default config like so.
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
Try this :
axios.get(
url,
{headers: {
"name" : "value"
}
}
)
.then((response) => {
var response = response.data;
},
(error) => {
var status = error.response.status
}
);
You are nearly correct, just adjust your code this way
const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });
notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side
Instead of calling axios.get function Use:
axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })
const response=await axios(url,
method:"GET"
{
headers: {
"Authorization" : `Bearer ${token}`
}
})
You can try this.
axios.get(
url,
{headers: {
"Access-Control-Allow-Origin" : "*",
"Content-type": "Application/json",
"Authorization": `Bearer ${your-token}`
}
}
)
.then((response) => {
var response = response.data;
},
(error) => {
var status = error.response.status
}
);
create a new axios instace for your request
const instance=axios.create({
baseURL:'www.google.com/'
headers:{
'Content-Type':'application/json',
'Acess-Control-Allow-Origin':'*',
'Authorization':`Bearer ${token}`,
'Accept': "application/json"
}
})
await instance.get(url,data)
Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.
This made it work:
cors = require('cors')
app.use(cors());
Original link
This is the Postman way of doing it:
headers: {
'Authorization': `Basic ${Buffer.from('username:password').toString('base64')}`
}
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote
: you have to add OPTIONS & Authorization to the setHeader()
this change has fixed my problem, just give a try!