3

I have axios get request with basic auth, but i keep getting back a 401 status code. My code does work if i am doing a post request, so I don't know what i'm doing wrong here.

My backend code:

app.get('/api/find-user', (req, res) => {
    const username = req.body.username;
    axios.get('my-url', username, {
        auth:{
            username: 'my-username',
            password: 'my-password'
        }
    })
    .then(resp => {
        res.json({resp});
    })
    .catch(error => {
        res.send(error.response.status);
    })
});

My frontend code:

findUser(user){
    const username = user;
    axios.get('/api/find-user', {username})
        .then(resp => {
            console.log(resp);
        })
        .catch(error => {
            console.log(error)
        })
}

Again when i am doing a post to create a new user it does work, but when i am doing a GET request it keeps saying i am not authorized.

Edit: If you feel like downvoting be adult enough to explain why.

djamaile
  • 695
  • 3
  • 12
  • 30
  • I had the same problem, just installed `qs` and parset the body as: `let body = qs.stringify(params)` as the params were my username and password. http://npmjs.com/package/qs – cassmtnr Dec 27 '18 at 02:55

3 Answers3

9

You need to do:

const usernamePasswordBuffer = Buffer.from(username + ':' + password);
const base64data = usernamePasswordBuffer.toString('base64');
const axiosObject = axios.create({
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${base64data}`,
    }
});

Because Axios needs the auth to be "encrypted" with both username and password.

Karen Garcia
  • 101
  • 4
1

For GET request you don't have a data object. You need send your params in config like this:

axios.get('my-url', {
    auth: {
        username: 'my-username',
        password: 'my-password'
    },
    params: { username }
})
Jonny
  • 11
  • 2
-1

There’s quite a few potential causes here. I think it might be helpful to state which API you’re trying to access. For instance:

  • do you definitely have READ access granted for your account on the API server?
  • your POST request isn’t using a password so is your password definitely correct for the GET?
James Howell
  • 1,392
  • 5
  • 24
  • 42
  • I'm using the Jira api, https://docs.atlassian.com/software/jira/docs/api/REST/7.10.0/#api/2/user-getUser – djamaile Nov 09 '18 at 09:40