Bearer Token
Contents

What is a bearer token?

The word “bearer” means exactly what it sounds like: whoever holds the token has access. It works like a digital key or a ticket, once you have it, you can enter the protected resources without having to prove who you are every single time.

This convenience makes bearer tokens ideal for mobile apps, modern web APIs, and complex systems with many services (microservices).

How bearer tokens work

A bearer token is like a digital ticket that grants access to protected resources. Here is the typical lifecycle, from creation to validation:

1. Issuing the token

The process starts when a client (like a mobile app or a service) proves its identity to an authorization server.
– Authentication: The client proves who they are, perhaps using a username and password, or by completing a complex flow like OAuth 2.0.
– Token creation: Once authentication succeeds, the server issues an access token. This token is usually marked with the label token_type: Bearer.
– Token format: The token itself might be a simple, opaque string, or it might be a structured token, like a JSON Web Token (JWT). A structured token contains useful information (called claims) inside it, such as the user’s ID, its expiry time, and its permissions (scope).

2. Using the token

The client uses the token to access the protected API (the resource server).
– Request header: The client includes the token in the HTTP request using the Authorization header in this specific format:

Authorization: Bearer <token_value>

– Access: The request is sent to the API, which uses the presence of the token to decide whether the requester has the necessary rights to view the resource.

3. Validating the token

The API (the resource server) performs crucial security checks every time a token is received:
Format and expiry: The server first checks if the token is properly formed and, most importantly, if it has expired.
– Permissions check: The server checks if the token grants the required scope/permissions needed for the specific action the client is trying to perform.
– Issuer check: It checks if the token was issued by the correct authorisation server and is meant for this specific API (audience).
– Validation method: Validation can be done locally (e.g., by checking the digital signature on a JWT) or by asking the original authorisation server if the token is still valid (called introspection).
– Outcome: If all checks pass, the request proceeds. If any check fails, the server returns an error, typically HTTP 401 Unauthorized.

4. Statelessness and scalability

Since structured bearer tokens carry their own security and claim information, the API can often validate them without needing to look up a session database on every single request. This makes the architecture stateless and much more scalable for large systems, mobile backends, and microservices.

I’d be delighted to rewrite this explanation of the benefits and risks of bearer tokens for you, ensuring the language is clear, actionable, and uses simple UK English.

Key benefits of bearer tokens

Bearer tokens are popular for modern systems because they solve major architectural challenges:
– Simplified access flow: Once a token is issued, the client can access protected resources repeatedly without having to re-authenticate (prove its identity) on every single request. This makes the user experience faster.
– Scalability: Tokens support stateless architectures. The server doesn’t need to maintain or look up session data for every client request, which allows systems (especially microservices) to scale horizontally much more easily.
– Modern compatibility: Bearer tokens work seamlessly across different platforms (web, mobile) and are the standard choice for modern APIs and distributed systems.

Risks and limitations

However, the convenience of a bearer token is also its greatest weakness:
Possession equals access: The fundamental risk is that possession of the token grants immediate authorisation. If a token is stolen or intercepted, the attacker gains the same access the legitimate user has.
– Exposure: Transmitting tokens over plain HTTP (instead of secure HTTPS) or storing them insecurely (e.g., in browser local storage where they are vulnerable to XSS attacks) drastically increases the chance of compromise.
– Amplified damage: Tokens that have overly long lifespans or grant broad, unnecessary permissions (scopes) will cause much greater damage if they are compromised.

Best practices for security

To effectively manage the risks associated with bearer tokens, apply these crucial security practices:
– Always use HTTPS (TLS): This is non-negotiable. Encrypt all API calls that carry bearer tokens to prevent interception during transit.
– Limit token lifetime (Expiry): Set a short expiry time on tokens so that if one is compromised, it quickly becomes useless.
– Use scopes/permissions: Grant only the minimum level of access needed for the token’s purpose (principle of least privilege).
– Secure client-side storage: Avoid storing tokens in places that are vulnerable (like easily accessible browser storage) to prevent exposure to attacks like XSS (Cross-Site Scripting).
– Provide revocation: Implement a token revocation mechanism so that if you detect a token has been stolen or compromised, you can quickly invalidate it on the server side.

Implementation example

This Python example uses the requests library to make a GET request, demonstrating the correct way to format the Authorization header using an f-string:

import requests

# Assume 'access_token' holds your valid Bearer Token
access_token = "your_secret_bearer_token_here" 

url = "https://api.sportmonks.com/v3/football/livescores"

headers = {
    # Key formatting is critical: "Authorization"
    # Value format is critical: "Bearer " followed by the token
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    data = response.json()
    # Process the data
    print("Success! Data received.")
else:
    print("Error:", response.status_code, response.text)

Implementation Example (.NET C#)

In .NET, you typically use the HttpClient and the AuthenticationHeaderValue class to handle the proper formatting, ensuring correctness:

using System.Net.Http.Headers;

// Assume 'token' holds your valid Bearer Token
string token = "your_secret_bearer_token_here";

var httpClient = new HttpClient();

// Using AuthenticationHeaderValue ensures the correct "Bearer <token>" format
httpClient.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", token);

var response = await httpClient.GetAsync("https://api.example.com/resource");

// Further logic to handle response
if (response.IsSuccessStatusCode)
{
    // Success logic...
}

Common patterns and tips

Header format: The header key must be exactly Authorization, and the value must strictly be Bearer <token>, including the exact casing and the required space after “Bearer.”
Use libraries: Whenever possible, use standard request libraries or SDKs for your chosen language. They often abstract away manual header formatting, reducing the chance of error.
– Security first: Never hardcode or expose your tokens. Store them securely:
    For server applications: Use environment variables, secret managers, or secure vaults.
    For client applications: Use secure memory, browser storage (with caution), or secure cookies.
Error handling: Always be prepared to handle an HTTP 401 Unauthorized response. This typically means the token is missing, expired, or invalid, and should trigger a token refresh or a full re-authentication flow.

Sportmonks’ Bearer Token Authentication

At Sportmonks, we use a bearer-style API token to secure access to our platform. This system allows for simple, flexible, and secure integration with all our data services.

How we handle authentication

When you subscribe to a plan, you generate a unique API token in your dashboard. This token acts as your digital key (the bearer token) for accessing our data.

You have two simple ways to send this token with every request:
– Via the query parameter: You include the token directly in the URL. This is the simplest method for quick testing.

https://api.sportmonks.com/v3/football/livescores?api_token=YOUR_TOKEN
Via the HTTP Header: You include the token in the Authorization header. This is the cleaner, more secure method for production code.

Authorization: YOUR_TOKEN

Every API request you make is authenticated using this token. We check your plan access and either fulfil the request or reject it if the token is invalid or if you’ve exceeded your quota.

Example endpoint Call: Get Live Scores

Let’s look at a practical example for fetching live scores:

Endpoint URL Format: https://api.sportmonks.com/v3/football/livescores?api_token=YOUR_TOKEN

What it does: Returns current live matches, scores, and related data based on the level of your subscription.

Usage steps

  1. Get token: Obtain your token from your MySportmonks dashboard. Keep it safe, we only show it to you once.
  2. Request: Insert the token into your request using either the query parameter or the header.
  3. Secure connection: Always make your GET request over HTTPS (we enforce secure connection).
  4. Inspect: A successful call returns HTTP 200 OK. If you receive HTTP 401 Unauthorized or HTTP 403 Forbidden, check your token, plan access, or rate limits.

Developer guidelines for using our token

Follow these rules to ensure your integration is secure and efficient:
Treat it as a secret: Store your token in secure locations like environment variables or a secure vault, never directly in code that is public-facing.
Always use HTTPS: This is mandatory. Using HTTPS ensures your token is encrypted and not exposed to eavesdropping.
Monitor usage: Keep track of your usage. If you exceed your limits, our API will return HTTP 429 Too Many Requests. Planning ahead helps you avoid service disruptions.
Hide from frontend: If you are building a web frontend, use a backend proxy or middleware to fetch the data. This hides the token entirely from the client’s side, eliminating the risk of public exposure.

Why our token model works

Our model provides you with powerful benefits:
Quick integration: Once the token is set up, you can make calls instantly.
Strong control: We can control precisely what data you receive (based on your plan) without requiring a full user login for every action.
High performance: We avoid heavy session-state logic on our end, meaning your token carries the access data, which helps us maintain performance and availability for all users.
Full responsibility: You generate and store the token securely, and you have the ability to revoke or regenerate it if needed.

Faqs about Bearer Tokens

What are bearer tokens?
Bearer tokens are access tokens that allow clients to authenticate and access protected API resources.
How do you get a bearer token?
You usually obtain one after successful login or OAuth authentication from the API’s authorization server.
Are OAuth and bearer token the same?
Not exactly, OAuth is the framework for authorization, while a bearer token is the credential it issues.
Is bearer token the same as API key?
No, API keys identify the client, while bearer tokens prove user authorization and typically expire after a set time.

Written by David Jaja

David Jaja is a technical content manager at Sportmonks, where he makes complex football data easier to understand for developers and businesses. With a background in frontend development and technical writing, he helps bridge the gap between technology and sports data. Through clear, insightful content, he ensures Sportmonks' APIs are accessible and easy to use, empowering developers to build standout football applications