Reputation: 329
I'm fairly new to react native so be gentle please :)
I need to pass a token to the authorization header - this is what i have just now which doesn't work:
const auth = new Buffer('username : <SECRETKEYHERE>');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
fetch('https://example.com/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
}).then((response) => response.text())
.then((responseText) => {
alert(responseText);
console.log(responseText);
})
(Note: The base64 conversion above works as expected and returns the correct base64 key, so that isn't the issue)
However, if i put the base64 key straight into the authorization header the request works as expected:
fetch('https://example.com/get-token.php', {
method: 'POST',
headers: {
'Authorization': 'Basic <BASE64KEYHERE>',
'Content-Type': 'application/json'
},
}).then((response) => response.text())
.then((responseText) => {
alert(responseText);
console.log(responseText);
})
I have searched SO and tried various solutions with no luck, main ones i have already looked at:
Using an authorization header with Fetch in React Native
React native - FETCH - Authorization header not working
If anyone can help or point me in the right direction it would be greatly appreciated as i have spent a fair bit of time trying to get this to work with no joy.
Upvotes: 0
Views: 1437
Reputation: 1018
Usually the format of HTTP Basic Authentication header is
Authorization:Basic <Base64EncodedAuthString>
where
Base64EncodedAuthString:=<username>:<password>
So I am wondering about the blanks before and after your colon in
const auth = new Buffer('username : <SECRETKEYHERE>');
, shouldn't it be
const auth = new Buffer('username:<SECRETKEYHERE>');
instead?
See also https://www.rfc-editor.org/rfc/rfc7617#page-5
Upvotes: 1