I want to send a post with fetching. But I get 401 error: www-authenticate: Bearer error="invalid_token".
I am using Userfront.accessToken() but It did not work.
How can I get accestoken for bearer authentication?
const submit = (e) => {
e.preventDefault();
const data = new FormData(form.current);
fetch(process.env.REACT_APP_ENDPOINT + "user/me/contract", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Userfront.accessToken()}`,
},
}).then((res) => res.json());
};
Note:
console.log(`Bearer ${Userfront.accessToken()}`);
Bearer [object Object]
Can you try this? I see this from https://userfront.com/guide/auth/
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
JSON.stringify(Userfront.accessToken()) please stringify that object to understand what is going on there then if there is accessToken returning from that function put that string.
I just realized in the doc;
To handle a request like this -Userfront.accessToken()-, your backend should read the JWT from
the Authorization header and verify that it is valid using the public
key found in your Userfront dashboard.
https://userfront.com/guide/auth/
fetch('https://api.example.com', {
method: 'GET'
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Userfront.tokens.accessToken}`
}
});
Thank you all for your answers.
Authorization: `Bearer ${localStorage.getItem("fray_access_token")}`,
In this application, token gets a different name.
When I look from inspects, I use it and it works!
Related
I'm trying to understand how the Discord API works, and I'm struggling to send a message in a channel. the code executes fine, but the message is not being sent. I tried with this code:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
body: content,
headers: this.headers,
});
but it doesn't work. What am i doing wrong?
content is the string I want to send, it's a function parameter and so is channel_id.
headers is:
{
authorization: `Bot ${token}`,
accept: "*/*",
};
The request returns a status code of 400 (Bad request).
I solved it. The issue is that I didn't specify the Content-Type of the request, and passed the content as a string. I added to the headers: "content-type": "application/json", and to the body I passed a Json object of the content:
await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
method: "POST",
headers: this.headers,
body: json({ content }),
});
And the headers:
this.headers = {
authorization: `Bot ${token}`,
"content-type": "application/json",
};
I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});
how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})
The issue is basically that the fetch response object is not correct. Pictures to clarify the issue are below as it is hard to explain.
My fetch request code.
fetch(this.constructUrl(url), {
method: method,
mode: 'no-cors',
headers: new Headers({
'Authorization': 'Bearer ' + this.token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}),
body: new FormData(document.getElementById(formIdentifier))
}).then(function (response) {
if (response.ok) {
return response.json().then(callback);
}
console.log(response);
}).catch(function(error) {
console.log(error);
});
The fetch response object.
The chrome response/request details
The chrome response data
So as you can see, the data in chrome looks correct but for some reason, the fetch response object does not seem to reflect what chrome picks up.
I had to switch 'no-cors' to 'cors' and allow cors in my rest stack.
I've been developing a mobile complement to my web application built with Rails. Using Fetch API, I keep getting the notice "Can't verify CSRF token authenticity".
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({user})
})
// promise handling
}
Edit: Managed to get it to work but I still don't really understand why. If anyone has the same problem, this is how I resolved it. I managed to get the form_authenticity_token from my rails application and saved it as a variable that I then passed to the function. Haven't tested removing the credentials key.
export const login = (user, token) => {
return fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ user, authenticity_token: token })
})
You need to add CSRF token in headers or disable / remove CSRF on cross domain request.
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({user})
})
// promise handling
}
When working with Django backend you should set:
'X-CSRFToken': csrf_token // not 'X-CSRF-Token' !!!
in your JS request headers.
Environment:
To set the token on the backend side, use:
{% csrf_token %} <!-- put this in your html template -->
And then, to get the token in the JS code:
const csrf_token = document.getElementsByName('csrfmiddlewaretoken')[0].value;