Bearer Authentication in React

13,953

Solution 1

The way headers are set is by providing the header item name and value, try:

showTransactionList = () => {
    superagent
        .post('http://193.124.114.46:3001/api/protected/transactions')
        .set('Authorization', 'Bearer ' + this.state.id_token)
        .accept('application/json')
        .then(res => {
            const posts = JSON.stringify(res.body);
            console.log(posts);
        })
        .catch((err) => {
            console.log(err);
            throw err;                    
        });
}

So instead of setting the object in the header, pass it as 2 parameters (name, value).

Solution 2

rather than setting the full header with

.set({'Authorization': 'Bearer ' + this.state.id_token})

you can use

.auth(this.state.id_token, { type: 'bearer' })

Share:
13,953
Andrew Fleyer
Author by

Andrew Fleyer

Updated on June 04, 2022

Comments

  • Andrew Fleyer
    Andrew Fleyer almost 2 years

    How can I use Bearer Authentication with superagent in React? I am not sure in syntax and can't find an example.

    What I do now

       showTransactionList = () => {
            superagent
                .post('http://193.124.114.46:3001/api/protected/transactions')
                .set({'Authorization': 'Bearer ' + this.state.id_token})
                .accept('application/json')
                .then(res => {
                    const posts = JSON.stringify(res.body);
                    console.log(posts);
                })
                .catch((err) => {
                    console.log(err);
                    throw err;                    
                });
        }

    Thnx!

  • Andrew Fleyer
    Andrew Fleyer over 5 years
    no. it doesn't help. response the same Error: "Unauthorized"
  • Rikin
    Rikin over 5 years
    Are you able to see any Auth being added in the HTTP request in console or possibly any proxy?
  • Andrew Fleyer
    Andrew Fleyer over 5 years
    The same result.
  • Bilal
    Bilal over 5 years
    Then probably you should use the (superagent-auth-bearer) plugin which is provided for this purpose npmjs.com/package/superagent-auth-bearer
  • Andrew Fleyer
    Andrew Fleyer over 5 years
    sending SET not like a single object was useful. Thanks