The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.
To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
It turns out, I was using the fetch
method incorrectly.
fetch
expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.
I was wrapping the intended object within a second object, which did not get me any desired result.
Here's how it looks on a high level:
fetch('API_ENDPOINT', OBJECT)
.then(function(res) {
return res.json();
})
.then(function(resJson) {
return resJson;
})
I structured my object as such:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': '',
'Host': 'api.producthunt.com'
},
body: JSON.stringify({
'client_id': '(API KEY)',
'client_secret': '(API SECRET)',
'grant_type': 'client_credentials'
})
}
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With