djamaile
djamaile

Reputation: 752

Axios: Basic auth not working with GET request

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.

Upvotes: 5

Views: 26183

Answers (5)

Ansuman Das
Ansuman Das

Reputation: 1

app.get("/basicAuth", async(req,res) =>{
    
    try{
    
    const jsObj = await axios.get("API_URL", {
    
    auth: {
      
     username: "username"
    
     passowrd: "password"
    
    },
    
});

Upvotes: 0

Yusuf Yasir
Yusuf Yasir

Reputation: 11

This worked pretty well for me

const response = await axios.get('url', {
  auth: {
    username: 'Jane',
    password: 'doe'
  },
});
const result = response.data;

Upvotes: 0

Jonny
Jonny

Reputation: 51

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 }
})

Upvotes: 5

Karen Garcia
Karen Garcia

Reputation: 121

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.

Upvotes: 11

James Howell
James Howell

Reputation: 1442

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?

Upvotes: 0

Related Questions