WTF is Bearer Token: An In-Depth Explanation

Arun Chaitanya
4 min readJul 3, 2023

--

In the world of web authentication and authorization, you might have come across the term “Bearer token.” But what exactly does it mean? How does it work? And why is the word “Bearer” attached before the token? In this article, we’ll dive deep into the world of Bearer tokens, exploring their purpose, implementation, and best practices.

Understanding Bearer Tokens

Bearer tokens are a type of authentication scheme used to identify the type of token being used for authentication and authorization. They are commonly used with the OAuth 2.0 protocol and other token-based authentication systems.

When a user or client is authenticated, they receive a token from the server. This token serves as proof of their authentication and is used to access protected resources on a web server. The Bearer token is typically included in the “Authorization” header of an HTTP request.

To indicate that the token being sent in the request is of type “Bearer,” the word “Bearer” is appended before the actual token in the “Authorization” header. Here’s an example of the format of the “Authorization” header with a Bearer token:

Authorization: Bearer <token>

In this example, <token> represents the actual token issued to the client by the authentication server. The web server receiving the request can then extract and validate the token, granting access to the requested resource if the token is valid and authorized.

Why is “Bearer” Attached Before the Token?

Attaching the word “Bearer” before the token in the “Authorization” header serves two important purposes:

  1. Identification: The “Bearer” keyword helps the server easily identify the type of token being used and handle it appropriately during the authentication and authorization processes. By including “Bearer,” the server can distinguish Bearer tokens from other types of tokens and apply the correct validation and authorization logic.
  2. Standardization: The use of the “Bearer” scheme is a widely adopted convention and a recommended practice for clarity and standardization. It promotes interoperability between different systems and components involved in the authentication flow, reducing the chances of misinterpretation or miscommunication.

Is Attaching “Bearer” Necessary?

While technically it may be possible to authenticate without explicitly including the “Bearer” keyword, it is strongly recommended to include it for proper authentication using the Bearer token scheme. Attaching “Bearer” before the token ensures clarity, consistency, and compatibility across different implementations and systems.

When the server receives an HTTP request with the “Authorization” header, it checks for the presence of the “Bearer” keyword to determine the authentication scheme being used. Without the “Bearer” keyword, the server may not recognize the token as a Bearer token and may fail to authenticate or authorize the request properly.

Therefore, always include the “Bearer” keyword before the token in the “Authorization” header to ensure that the server can handle the token appropriately.

Implementing Bearer Tokens

Implementing bearer tokens in your web application involves generating, issuing, and validating the tokens. Here’s an example of generating and issuing a bearer token using Node.js and the Express framework:

// Generate and issue a bearer token
function issueToken(userId) {
const token = jwt.sign({ userId }, 'your-secret-key', { expiresIn: '1h' });
return token;
}

// Example usage
const userId = '123456789';
const token = issueToken(userId);
console.log('Bearer token:', token);

In this example, the issueToken the function generates a bearer token using the jsonwebtoken library. The token is signed with a secret key and includes the user ID as the payload. Adjust the secret key and payload according to your application's requirements.

To protect a route using bearer token authentication, you can use middleware to validate the token before granting access to the protected resource. Here’s an example using Node.js and Express:

// Middleware for bearer token authentication
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];

if (!token) {
return res.sendStatus(401);
}

jwt.verify(token, 'your-secret-key', (err, decoded) => {
if (err) {
return res.sendStatus(403);
}

// Add the decoded information to the request object
req.user = decoded;
next();
});
}

// Protected route
app.get('/api/protected-resource', authenticateToken, (req, res) => {
// Access the user information from req.user
const userId = req.user.userId;
// Fetch the protected resource and send the response
res.json({ message: `Protected resource accessed by user ${userId}` });
});

In this example, the authenticateToken middleware validates the bearer token by verifying it using the same secret key used during token generation. If the token is valid, the middleware adds the decoded information to the request object (req.user), allowing access to the protected route.

Remember to replace 'your-secret-key' with a strong secret key and adjust the route and resource logic according to your application's requirements.

Conclusion

Bearer tokens play a crucial role in web authentication and authorization, allowing users or clients to access protected resources. By appending the word “Bearer” before the token in the “Authorization” header, we provide a clear identification of the token type and ensure compatibility and standardization across different systems.

While attaching “Bearer” before the token is not technically required, it is highly recommended for proper authentication using the Bearer token scheme. By following this convention, we improve clarity, consistency, and interoperability, resulting in more secure and robust authentication systems.

So, the next time you encounter the term “Bearer token,” you’ll have a solid understanding of what it means and why it is important in web authentication.

--

--

Arun Chaitanya

A passionate web developer driven by curiosity and a love for continuous learning.