How to send bearer token in a header with Axios

How to send bearer token in a header with Axios

How to send bearer token in header with axios

While there is an increase in the number of users who gain access to the world wide web, it has become more important for web and app developers to provide a secure environment for their users. Authorizing and authenticating users helps secure a user's information from being hijacked.

In my previous article, I gave an insight into what Axios is and how to use it to make basic API calls. In this article we'll discuss how to send bearer tokens. That being said, let's get started.

What is a token?

A token is used to provide authentication and authorization to a user when accessing a specific network. Tokens are always generated as an OTP (One-Time Password), which can only be used once and is generated at random for each transaction.

Token-based authentication allows users to verify their unique identity in exchange for a unique token that grants them access to specific resources for a set period of time.

How Tokens Work?

We are required to provide our credentials before we can complete a transaction on a web or mobile application. After we enter our credentials, the system compares them to the credentials already in the database. A token generator generates a random OTP. The system sends the generated OTP to our mobile device via text message or email. If our input matches the existing credentials, then we are authenticated.

How do we send a bearer token in a header?

To use the Bearer Token authorization header, make an HTTP request and include your Bearer Token in the "Authorization: Bearer Token" header. A Bearer Token is a cryptic string that the server generates in response to a login request.

const api = 'your api url'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , 
            { headers: {"Authorization" : `Bearer ${token}`} 
})
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

The preceding code snippet demonstrates a basic method of sending a bearer token in a header. Please keep in mind that the Axios library must be installed and imported into your project.

Conclusion

In conclusion, keep an eye out for more discussion about authorization, authentication, identification (ID) token and access token.

Please leave a comment if you found this useful. I am open to suggestions for alternative methods of sending a token in a header.