Basic Auth Using the Axios HTTP Client | Axios Authentication

In this tutorial, we will see how to use Basic Auth using the Axios HTTP client. Axios has built-in support for basic auth. Axios provides a way to request APIs protected with basic auth, and hides the base64 encoding and string concatenation. And Basic Auth is a way to handle logging/signing in using username and password via http. Axios provides basic auth for free of cost. Free sample endpoint is given by HTTPBin to test basic auth. Accurate username and password are required for testing purposes.

If we pass the auth option to axios.get(), axios will format basic auth .

Code without Error Handling

const res = await axios.get('https://httpbin.org/basic-auth/foo/bar', {
  auth: {
    username: 'foo',
    password: 'bar'
  }
});
res.status; // 200

Suppose if login failed, HTTPBin responds with an HTTP 401 call, which Axios bubbles up as a promise rejection.

Code with Error Handling

const err = await axios.
  get('https://httpbin.org/basic-auth/foo/bar', {
    auth: {
      username: 'foo',
      password: 'baz' // wrong password
    }
  }).
  catch(err => err);

console.log(err.message); // "Request failed with status code 401"
console.log(err.response.status); // 401 "Unauthorized"

The code given below is also equivalent to the one written above ;

Final Code (with Success & Error Handling)

var session_url = 'http://api_address/api/session_endpoint'; 
var uname = 'user';
 var pass = 'password'; 
axios.post(session_url, {}, { 
auth: 
{ 
username: ", 
password: pass
 } 
}).then(function(response)
 { console.log('Authenticated'); 
}).catch(function(error) 
{ 
console.log('Error on Authentication');
 });

Hope you have understood the code. Comment below if you have any queries.

Suitable For: React JS or any other JS framework.

1 thought on “Basic Auth Using the Axios HTTP Client | Axios Authentication”

Leave a Comment