0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

i removed the blanks and i'm now getting a successful request. I should have tried that! haha. Thanks for your time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.