How to send an authorization header with Axios

Dec 05, 2023#axios#node#http

Axios is a JavaScript library that allows you to make HTTP requests from your browser or Node.js server, often used to communicate with RESTful APIs, fetch data, upload files, etc.

Axios supports the Promise API, which means you can write asynchronous code in a more readable and elegant way. It also has some useful features, such as setting default headers, intercepting requests and responses, canceling requests, and transforming request and response data.

To include an authorization header using Axios, you can use the headers configuration option per request. You can also set the default header option for the Axios global object, so that every Axios request will have the Authorization header.

Using Basic Auth

Basic auth is not token-based, but it is similar in some ways. Basic auth is a type of HTTP authentication scheme that uses a username and password pair to authenticate a user or a client to a server.

The username and password are joined by a single colon :, then encoded using Base64 and sent in the Authorization header of the HTTP request.

To send Basic auth with Axios, you can do something like this:

const axios = require('axios');

// Set username and password
const username = 'user';
const password = 'pass';

// Encode username and password in base64
const encoded = Buffer.from(username + ':' + password).toString('base64');

axios.get('https://example.com/api', {
    headers: {
      'Authorization': 'Basic ' + encoded
    }
  })
  .then(response => {
    // Handle success
    console.log(response.data);
  })
  .catch(error => {
    // Handle error
    console.error(error);
  });

Another way is to use the auth parameter in the request options object, which will automatically encode and set the authorization header for you, overwriting any existing Authorization custom headers you have set using headers.

const axios = require('axios');

axios.get('https://example.com/api', { 
    auth: {
      username: 'user',
      password: 'pass'
    } 
  })
  .then(response => {
    // Handle success
  })
  .catch(error => {
    // Handle error
  });

Basic auth is not secure because the username and password are passed over the network as clear text, which can be easily intercepted and decoded. Therefore, Basic auth should only be used over HTTPS, which encrypts the data in transit.

Using Bearer Token

Token-based authentication uses a token, which is a cryptic string that represents the user’s identity and permissions. The token is usually generated by the server in response to a login request, and can be verified by the server without requiring the user to provide their credentials again. The token is sent in the Authorization header of the HTTP request, with the prefix “Bearer”.

If you want to send a Bearer token with Axios, you can do something like this:

const axios = require('axios');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

axios.get('https://example.com/api', { 
    headers: {
      'Authorization': 'Bearer ' + token
    } 
  })
  .then(response => {
    // Handle success
  })
  .catch(error => {
    // Handle error
  });

This method is more secure than Basic auth because the token is not directly related to the user’s credentials, and can be revoked or expired by the server at any time. However, token-based authentication should also be used over HTTPS, to prevent the token from being stolen or tampered with.

One type of token that is commonly used is JSON Web Token (JWT), which contains a JSON data payload that can be signed and encrypted. A JWT has a standard structure that consists of three parts: a header, a payload, and a signature. The header specifies the type and the algorithm of the token, the payload contains the claims or the data of the token, and the signature verifies the integrity and authenticity of the token.