How to send Basic Auth with axios

Emmanuel  picture Emmanuel · May 19, 2017 · Viewed 186.3k times · Source

I'm trying to implement the following code, but something is not working. Here is the code:

  var session_url = 'http://api_address/api/session_endpoint';
  var username = 'user';
  var password = 'password';
  var credentials = btoa(username + ':' + password);
  var basicAuth = 'Basic ' + credentials;
  axios.post(session_url, {
    headers: { 'Authorization': + basicAuth }
  }).then(function(response) {
    console.log('Authenticated');
  }).catch(function(error) {
    console.log('Error on Authentication');
  });

It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I don't fill those fields it also returns 401, but if I do, the request is successful.

Any ideas what I'm doing wrong?

Here is part of the docs of the API of how to implement this:

This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.*

Answer

luschn picture luschn · May 29, 2017

There is an "auth" parameter for Basic Auth:

auth: {
  username: 'janedoe',
  password: 's00pers3cret'
}

Source/Docs: https://github.com/mzabriskie/axios

Example:

await axios.post(session_url, {}, {
  auth: {
    username: uname,
    password: pass
  }
});